gpt4 book ai didi

kotlin - 委派给初始化属性时出现 "Variable must be initialized"错误

转载 作者:IT老高 更新时间:2023-10-28 13:39:00 28 4
gpt4 key购买 nike

object Foo : CharSequence by Foo.X {
val X = ""
}

产生

Variable 'X' must be initialized

但确实如此!并且代码应该翻译成类似

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)
}

效果很好。

错误的原因是什么,是否有解决方法?在真正的代码初始化中是不平凡的,Foo 需要是一个 object(实际上是一个伴随对象),而不是一个 class

最佳答案

我推测在对象上使用类委托(delegate)有点不明显,所以这可能是为什么的本质。

一种解决方法是直接委托(delegate)给 String 的一个实例。这段代码对我有用:

fun main(args: Array<String>) {
println("Hello, world! ${Bar.Foo.indexOf("z")}") // Prints "2"
}

class Bar {
companion object Foo : CharSequence by String(StringBuilder("xyzzy")) {
}
}

旁白:Kotlin 中的 String 没有采用 String 参数的构造函数。奇怪,那个。

关于kotlin - 委派给初始化属性时出现 "Variable must be initialized"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47391856/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com