+ 7
The mystery of primary constructor in Kotlin. Please explain that code.
Can someone explain me this code please? https://code.sololearn.com/coeTwn3OWsl0/?ref=app
3 Respuestas
+ 14
Oma, in your case, primary constructor parameter "count" need to be marked as 'val' or 'var' :
class mystery(var count: Int = 0)
// in main function :
val myobj = mystery()
println(myobj.count )
When you write val/var within the constructor, it declares a property inside the class. When you do not write it, it is simply a parameter passed to the primary constructor, where you can access the parameters within the init block or use it to initialize other properties (for example "num" in class "mystery2" in your code)
+ 12
Oma Falk
That's right 😊
+ 7
LukArToDo
ok...,
but what is the mystery constructor worth for?
...ahh one thought: it can influent more than one property.
so a class receipt can receive a parameter for number of persons and all ingredient properties can be initialzed with the right amount(weight)
Am I right?