elect
11/06/2022, 9:40 AMcomment
which I'm initializing by delegation
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
sealed class Type(line: String, val comment: String = by line)
what's my best option for this?Sam
11/06/2022, 10:00 AMString
. But ignoring that problem, if I've understood what you're trying to do, a good solution might be something like this:
class Type(
line: String,
private val commentProvider: () -> String = { line }
) {
val comment get() = commentProvider.invoke()
}
elect
11/06/2022, 10:05 AMephemient
11/06/2022, 7:29 PMoperator fun <T> (() -> T).getValue(thisRef: Any?, property: KProperty<*>): T = invoke()
enables writing
val comment by commentProvider
but you can't do that in the constructorelect
11/07/2022, 1:56 AMilya.gorbunov
11/09/2022, 3:03 AMsealed class Type(line: String, val comment: String = line)
?elect
11/09/2022, 10:01 AMelect
11/09/2022, 10:01 AM