There isn’t a way to mix data classes and Delegate...
# announcements
s
There isn’t a way to mix data classes and Delegates (while retaining the type we delegate to), is there??
Copy code
fun 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/qfUC7Uzcj
m
in order for kotlin to understand lazyness and delegation, it will propegate to a wrapper. val name: String by lazy{"bla"} just means that name is of type: Lazy<String> what you could do is mask it
Copy code
data class Retailer(
        private var _name: Lazy<String>
) {
    val name: String
        get() = _name.value
    
    constructor(_name: String) : this(lazy{_name})
}
s
nice workaround, even though. On a different note: I think you’re mistaken here:
Copy code
val 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:
Copy code
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.
b
name
is of type
String
but it is backed by an internal property that is of type
Lazy<String>
.
Copy code
val name by lazy { "someName" }
is the same as
Copy code
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.
s
good to know the internals 👍 but technically I was right then 😅. Saying "name is of type: Lazy<String>" is wrong,
name
is of type
String
(backed by a getter)! It's
nameDelegate
that is of type
Lazy<String>
!