Spek - 变量未在测试中初始化

Spek - Variable not initialized in test

以下代码无法编译:

  describe("something") {
    context("when something") {
      var a: SomeType

      beforeEachTest { 
        a = someNewMutableObject
      }

      it("should do something") {
        assertTrue(a.something()) // variable a not initialized
      }
    }
  }

如何解决这个问题?我可以为变量分配什么来消除警告?

只需对要在使用前初始化的变量使用 lateinit 修饰符。

  describe("something") {
    context("when something") {

      lateinit var a: SomeType

      beforeEachTest { 
        a = someNewMutableObject
      }

      it("should do something") {
        assertTrue(a.something()) // variable a is okay to use here
      }
    }
  }

PS。 lateinit 局部变量仅适用于 Kotlin 1.2

在 Kotlin 1.1 中,您应该将其初始化为默认值或 null(也使其成为可空类型)。