我如何才能懒惰初始化字段并对其执行断言?
我试过了
val table: Array<FormatInfo> by lazy {
val t = arrayOf(...)
assert(table.size == FORMAT_COUNT, { System.err.println("GLI error: format descriptor list doesn't match number of supported formats") })
t
}
但是它会溢出:
java.lang.StackOverflowError
at gli.GliKt$table$2.invoke(gli.kt:451)
at gli.GliKt$table$2.invoke(gli.kt)
at kotlin.SynchronizedLazyImpl.getValue(Lazy.kt:131)
at gli.GliKt.getTable(gli.kt)
at gli.GliKt$table$2.invoke(gli.kt:693)
at gli.GliKt$table$2.invoke(gli.kt)
at kotlin.SynchronizedLazyImpl.getValue(Lazy.kt:131)
at gli.GliKt.getTable(gli.kt)
at gli.GliKt$table$2.invoke(gli.kt:693)...
我该如何解决?
最佳答案
堆栈跟踪看起来就像您从lazy {}
lambda内部调用该属性一样,显然会使它粉碎。
这应该工作:
val table: Array<FormatInfo> by lazy {
val t = arrayOf(...)
myAssert(t)
t
}