Student of Kotlin

Asked

Viewed 190 times

0

I am studying Kotlin and I am learning about builder, I would like to know what the difference is and when is used a primary builder and a secondary builder

examples:

Init Constructor And set straight in class: class House(var color: String, var vagaGaragem: Int)

if you can explain in a simple way with simple examples helps me to understand better

thank you

1 answer

3


A class in Kotlin may have a primary constructor and one or more secondary constructors.

In Kotlin it is possible to create classes with properties using only one line of code for this use the primary constructor to declare the properties.

data class Person(val firstName: String, val lastName: String)

If you need to execute some code in the primary constructor in addition to declaring properties, you use an init keyword initializer block.

data class Person(val firstName: String, val lastName: String) {
    init {
        println("Person criado, $firstName $lastName")
    }
}

Secondary constructors are used for when you want to instantiate the same class in different ways.

class Person {
    var firstName: String = ""
    var lastName: String = ""

    constructor() {
        firstName = "José"
        lastName = "Silva"
    }

    constructor(name: String) {
        firstName = name
        lastName = "Silva"
    }

    constructor(name: String, last: String) {
        firstName = name
        lastName = last
    }
}

fun main() {
    val person1 = Person()
    val person2 = Person("João")
    val person3 = Person("Marcos", "Santos")

    println("${person1.firstName} ${person1.lastName}")

    println("${person2.firstName} ${person2.lastName}")

    println("${person3.firstName} ${person3.lastName}")
}

If the class already has a primary constructor, each secondary constructor will need to delegate to the primary constructor using this keyword.

class Person(var firstName: String, var lastName: String) {
    init {
        println("Este bloco será executado primeiro :p")
    }

    constructor() : this("José", "Silva") {
        println("Chamei o construtor primário #1")
    }

    constructor(name: String) : this(name, "Silva") {
        println("Chamei o construtor primário #2")
    }

    constructor(name: String, last: String) : this(name, last) {
        println("Chamei o construtor primário #3")
    }    
}

fun main() {
    val person1 = Person()
    val person2 = Person("João")
    val person3 = Person("Marcos", "Santos")

    println("${person1.firstName} ${person1.lastName}")

    println("${person2.firstName} ${person2.lastName}")

    println("${person3.firstName} ${person3.lastName}")
}

For more information here is a link to the Kotlin documentation for classes: https://kotlinlang.org/docs/reference/classes.html

Browser other questions tagged

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