Search code examples
scalascalatest

Not Able to Compile When Mixing In A Trait When Using TableDrivenPropertyChecks


I am having trouble compiling the following code.

I am using TableDrivenPropertyChecks and I have something like this

trait MyTrait{

def foo: String

}

  "A X" should "do something correctly" in new MyTrait {

    val items =
      Table(
        "id",
          "1"
      )

    forAll(items) { item =>
      val foo = item
      //test condition
    }
}

The code fails with this message:

Object creation impossible since member value foo:String in MyTrait is not defined.

How can I fix this? If I put the override val foo outside the forAll with an arbitrary string it compiles e.g

  "A X" should "do something correctly" in new MyTrait {


val items =
  Table(
    "id",
      "1"
  )
override val foo = "1"  //compiles

forAll(items) { item =>

  //test condition
  }
}

UPDATE I have fixed this by doing this

      "A X" should "do something correctly" in {  // take out the new MyTrait here


    val items =
      Table(
        "id",
          "1"
      )

    forAll(items) { item =>
      new MyTrait {  //create my trait here
            override val value = item
      //test condition
}
      }
    }

But I would like to know why it fails


Solution

  • Your original example fails to compile due to scoping. If you create new MyTrait on the top scope, but define val foo = item inside the loop, then that val is just a local variable inside the closure. It's quite logical if you think about it, a single instance of MyTrait cannot possibly have multiple implementations of the same property. In your solution you create multiple instances of MyTrait and each of them gets a single, stable implementation of value.