instantiating a class, there is a field `comment` ...
# getting-started
e
instantiating a class, there is a field
comment
which I'm initializing by delegation
Copy code
sealed class Type(line: String) {
    val comment by line
However there might be some cases where I need to set it explicitly via constructor.. idiomatic code
Copy code
sealed class Type(line: String, val comment: String = by line)
what's my best option for this?
s
I'm guessing you have simplified this code before posting it? It doesn't work in this form because you can't delegate a property to a
String
. But ignoring that problem, if I've understood what you're trying to do, a good solution might be something like this:
Copy code
class Type(
    line: String, 
    private val commentProvider: () -> String = { line }
) {
    val comment get() = commentProvider.invoke()
}
e
nice idea, it seems at least the compiler is happy I'll try it and see where it goes, thanks Sam!
e
defining
Copy code
operator fun <T> (() -> T).getValue(thisRef: Any?, property: KProperty<*>): T = invoke()
enables writing
Copy code
val comment by commentProvider
but you can't do that in the constructor
e
but nice tip nonetheless, thanks
i
Why can't you write just
sealed class Type(line: String, val comment: String = line)
?
e
because I want it to be assigned via delegation
it's an xml