1

The following code does not compile:

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

      beforeEachTest { 
        a = someNewMutableObject
      }

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

How would one get around this problem? What could i assign to the variable to get rid of the warning?

Dylanthepiguy
  • 1,621
  • 18
  • 47

1 Answers1

1

Just use the lateinit modifier on the variable that will be initialised before use.

  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 local variables are available from Kotlin 1.2 only

In Kotlin 1.1 you should just initialise it to a default value or null (make it a nullable type also).

Dylanthepiguy
  • 1,621
  • 18
  • 47
Strelok
  • 50,229
  • 9
  • 102
  • 115