【问题标题】:Spek - Variable not initialized in testSpek - 变量未在测试中初始化
【发布时间】:2018-03-30 13:15:16
【问题描述】:

以下代码无法编译:

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

      beforeEachTest { 
        a = someNewMutableObject
      }

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

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

【问题讨论】:

    标签: kotlin spek


    【解决方案1】:

    只需对将在使用前初始化的变量使用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
          }
        }
      }
    

    附言。 lateinit 局部变量仅在 Kotlin 1.2 中可用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      • 1970-01-01
      • 2016-06-30
      • 1970-01-01
      • 2016-03-01
      • 2022-01-04
      • 2014-04-05
      相关资源
      最近更新 更多