是否可以懒惰地初始化属性并断言它?

时间:2016-10-29 11:59:13

标签: lazy-evaluation kotlin assert lazy-initialization

如何延迟初始化字段并对其执行断言?

我试过

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

我该如何解决?

1 个答案:

答案 0 :(得分:3)

堆栈跟踪看起来就像是从lazy {} lambda内部调用属性,这显然会让它变得迷恋。

这应该有效:

val table: Array<FormatInfo> by lazy {
   val t = arrayOf(...)
   myAssert(t)
   t
}