Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Variable must be initialized" error when delegating to an initialized property

Tags:

kotlin

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.

like image 407
Alexey Romanov Avatar asked Nov 20 '17 12:11

Alexey Romanov


1 Answers

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.

like image 83
Paul Hicks Avatar answered Sep 28 '22 13:09

Paul Hicks