What is the difference between init and constructor?

Asked

Viewed 242 times

9

I’m starting to learn Kotlin and I’d like to know the difference between init and constructor, or set directly in the example class:

class House(var cor: String, var vagaGaragem: Int)
  • The answer clarified your doubt?

1 answer

5

First of all, what you call "set straight in class" is a builder.

A class in Kotlin can have a primary constructor and "secondary constructors".

Primary constructors are like this of your example code: it is followed by the class name and can have parameters. These cannot have a code block, so the only way to write some startup code on them is by using the block init.

In addition, all boot blocks defined in the class will be executed for all builders in the order they are created.

Take an example:

fun main() {    
    var p = Person("Jeferson", 23)

    println("**************")

    var p2 = Person("Joaquim")
}

class Person(val name: String, val age: Int) { // <<= Construtor primário
    constructor(name: String) : this(name, 0) {  // <<= Construtor secundário
        println("Construtor 2")
    }

    init {
        println("Init 1")
    }

    init {
        println("Bloco Init 2")
    }
}

See working on Kotlin Playground

This will print on the screen

Init 1  
Bloco Init 2  
**************  
Init 1  
Bloco Init 2  
Construtor 2  
  • What do you mean, primary constructors cannot have code? I would like to understand, there is no code in the constructor itself used as an example?

  • @user140828 What code? There’s nothing there.

  • println is not considered code? I think I got it wrong, primary constructor would be the class statement itself?

  • @user140828 I put a comment to identify each constructor

Browser other questions tagged

You are not signed in. Login or sign up in order to post.