Moving variable to constructor


#1

This is a class I wrote in Kotlin

class Student() {
    var name : String?
    init {
        name = "Max"
    }
}

Android studio suggested me that I can “Move” this to constructor, and this is how it became after that

class Student(var name: String?) {
    init {
        name = "Max"
    }
}

Wait a minute! So a constructor parameter becomes a class variable?? Is that normal?

Also, in the first scenario, I can create a new object as

var stud = Student()

But if I move it to a constructor, I must specify a parameter whenever I create a new object, even if I don’t use it.

var stud = Student(“whatever”)

So how are these two equivalent? Or am I getting it totally wrong?


#2

You most likely want something like this:

class Student() {
    var name : String? = "Max"
}

Or maybe simply:

class Student() {
    var name = "Max"
}

#3

Yes, that would certainly work. I’m still learning Kotlin, playing around the formats and stumbled upon this, and it made me really confused.


#4

That suggested syntax is just a “shortcut” for defining the property in the body of the class and defining a constructor parameters for that property.

Because constructor parameters are like function parameters you have to provide a default for any parameter you want to skip.

Of course in your example making that change means that the name assignment in the init section is redundant and would override the property value assigned by the constructor.