blue
07/27/2020, 2:56 PMvar
) property during declaration?
*T*he study material says -
full syntax for any property in Kotlin:
var <propertyName>[: <PropertyType>] [= <property_initializer>]
[<getter>]
[<setter>]
Initializer, getter, and setter are optional here, but you need to initialize your variable if you don’t want to specify its type. Otherwise, the compiler will warn you.But my code snippet is throwing compile error. Did I miss something?
class User {
var firstName: String
var lastName: String
}
João Gonçalves
07/27/2020, 2:58 PMfirstName
and lastName
are of type String which means that they aren’t optional. For this reason, you either initialize the values or provide a constructor to initialize themthanksforallthefish
07/27/2020, 3:00 PMlateinit
you need an initial value. kotlin wants you to be explicit, basically you are assuming the responsibility of initializing the value before using the variableblue
07/27/2020, 3:01 PMInitializer, getter, and setter are optional here, but you need to initialize your variable if you don’t want to specify its type.
thanksforallthefish
07/27/2020, 3:01 PMclass User(var firstName: String, var lastName: String)
or
class User {
lateinit var firstName: String
lateinit var lastName: String
}
or
class User {
var firstName = ""
var lastName = ""
}
brandonmcansh
07/27/2020, 3:04 PMbrandonmcansh
07/27/2020, 3:04 PMdata class User(val firstName: String, val lastName: String)
pedro
07/27/2020, 3:05 PMclass Example(
private var property: String
) {
init {
property = "hello"
}
}
This is valid kotlin and the value is not initialised at the property declaration. So this might be nitpicking a bit but what they said is correctthanksforallthefish
07/27/2020, 3:10 PMinit
it is technically run during object initialization, so the property is initialized when the object is constructed.
also,
class Example(
private var property: String
)
is valid, because you need to pass a value when instantiating an Example
they refer to the syntax
class Example {
var property: String
}
but I don’t the sentence, initializer is not optional. ofc you can write
class Example {
var property: String
init { property = "" }
}
but a). nowhere in that page they mention the construct and b). init
is run at object initialization, so the initializer is therepedro
07/27/2020, 3:34 PMblock is calledWhat you said is correct but the original question is not talking about initialisation. Just declaration. I did say my answer was nitpicking 🙂 I still think this might be what they were thinking about when they wrote it.it is technically run during object initialization, so the property is initialized when the object is constructed.init
thanksforallthefish
07/28/2020, 6:30 AM