nucc
11/05/2017, 9:40 PMlazy
keyword that might can help for me, but I don't know how I could use it in a data class. I want something like in C++ how we define a const
instance variable in the constructor. Here is an example what I would like to do:
data class MyClass(val property: String) { # <-- mutable
init {
this.property = property.capitalize()
}
}
instance = MyClass("test")
instance.property # Test
instance.property = "test2" # error, immutable variable
but unfortunately the compiler says Val cannot be reassigned
when I set this.property
. Do you know how I could use immutable instance variable here?karelpeeters
11/05/2017, 9:44 PMval
means immutable, I think you're looking for var
.nucc
11/05/2017, 9:44 PMkarelpeeters
11/05/2017, 9:47 PMval
, it is already initalized by the main constructor itself.data class MyClass(property: String) {
val property = property.capitalize()
}
nucc
11/05/2017, 9:52 PMval
or var
before the constructor argument: Data class primary constructor must have only property (val / var) parameters
karelpeeters
11/05/2017, 9:53 PMAndreas Sinz
11/05/2017, 9:57 PMEduard Boloș
11/05/2017, 9:57 PMkarelpeeters
11/05/2017, 10:01 PMcopy
function leaks the constructor, so I'd be able to do MyClassFactory("test").copy(property = "test")
to get a "broken" instance.nucc
11/05/2017, 10:01 PMMyClass
object then I need to copy the logic everywhere. Or I should create a factory class, but I don't really want to create a MyClassFactory
just to do some modification on a string.karelpeeters
11/05/2017, 10:01 PM@NoCopy
annotation to avoid stuff like this.MyClass
, Kotlin allows it.nucc
11/05/2017, 10:03 PMEduard Boloș
11/05/2017, 10:04 PMnucc
11/05/2017, 10:05 PMkarelpeeters
11/05/2017, 10:05 PMMath.abs
.capitalize
either, consider MyClass("test") == MyClass("Test")
.nucc
11/05/2017, 10:07 PM