object Foo : CharSequence by Foo.X {
val X = ""
}
produces
Variable 'X' must be initialized
But it is! And the code should translate to something like
object Foo : CharSequence {
val X = ""
override val length get() = Foo.X.length
override operator fun get(index: Int): Char = Foo.X[index]
override fun subSequence(startIndex: Int, endIndex: Int) = Foo.X.subSequence(startIndex, endIndex)
}
which works well.
What is the reason for the error and is there a workaround? In real code initialization is non-trivial and Foo
needs to be an object
(actually, a companion object), not a class
.
I speculate that using class delegation on an object is a bit non-obvious, so that's probably the essence of why.
A workaround is to delegate directly to an instance of String. This code works for me:
fun main(args: Array<String>) {
println("Hello, world! ${Bar.Foo.indexOf("z")}") // Prints "2"
}
class Bar {
companion object Foo : CharSequence by String(StringBuilder("xyzzy")) {
}
}
Aside: String
in Kotlin has no constructor that takes a String parameter. Odd, that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With