Stephan Schroeder
02/26/2020, 10:12 AMfun main() {
val r1 = Retailer(name = "test")
val r2 = Retailer(name by lazy{"test"})
}
data class Retailer(
val name: String
)
Playground link: https://pl.kotl.in/qfUC7UzcjMichael de Kaste
02/26/2020, 10:30 AMMichael de Kaste
02/26/2020, 10:30 AMdata class Retailer(
private var _name: Lazy<String>
) {
val name: String
get() = _name.value
constructor(_name: String) : this(lazy{_name})
}Stephan Schroeder
02/26/2020, 11:20 AMval name: String by lazy{"bla"}
just means that name is of type: Lazy<String>
name is clearly of type String, otherwise this wouldn’t work:
fun main() {
val r3:String = Retailer2("test").name
}
class Retailer2(_name: String) {
val name: String by lazy{_name}
}
There is some lower level engineering going on when using by not mere assignment.Burkhard
02/26/2020, 4:54 PMname is of type String but it is backed by an internal property that is of type Lazy<String>.
val name by lazy { "someName" }
is the same as
private val nameDelegate = lazy{ "someName"}
val name: String
get() = nameDelegate.value
In truth there is some more “magic” behind the value part of the delegate passing in some more information about the delegated property, but it isn’t used here.Stephan Schroeder
03/29/2020, 11:13 AMname is of type String (backed by a getter)! It's nameDelegate that is of type Lazy<String>!