在使用 TableDrivenPropertyChecks 时混合特征时无法编译
Not Able to Compile When Mixing In A Trait When Using TableDrivenPropertyChecks
我在编译以下代码时遇到问题。
我正在使用 TableDrivenPropertyChecks,我有这样的东西
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
}
}
代码失败并显示此消息:
Object creation impossible since member value foo:String in MyTrait is not defined.
我该如何解决这个问题?如果我将 override val foo outside the forAll
与任意字符串一起编译,例如
"A X" should "do something correctly" in new MyTrait {
val items =
Table(
"id",
"1"
)
override val foo = "1" //compiles
forAll(items) { item =>
//test condition
}
}
更新
我已经通过这样做
解决了这个问题
"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
}
}
}
但是我想知道为什么会失败
您的原始示例由于范围界定而无法编译。如果您在顶层范围内创建 new MyTrait
,但在循环内定义 val foo = item
,那么该 val 只是闭包内的一个局部变量。如果您考虑一下,这是很合乎逻辑的,MyTrait
的单个实例不可能有相同 属性 的多个实现。在您的解决方案中,您创建了 MyTrait
的多个实例,并且每个实例都获得了 value
的单个稳定实现。
我在编译以下代码时遇到问题。
我正在使用 TableDrivenPropertyChecks,我有这样的东西
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
}
}
代码失败并显示此消息:
Object creation impossible since member value foo:String in MyTrait is not defined.
我该如何解决这个问题?如果我将 override val foo outside the forAll
与任意字符串一起编译,例如
"A X" should "do something correctly" in new MyTrait {
val items =
Table(
"id",
"1"
)
override val foo = "1" //compiles
forAll(items) { item =>
//test condition
}
}
更新 我已经通过这样做
解决了这个问题 "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
}
}
}
但是我想知道为什么会失败
您的原始示例由于范围界定而无法编译。如果您在顶层范围内创建 new MyTrait
,但在循环内定义 val foo = item
,那么该 val 只是闭包内的一个局部变量。如果您考虑一下,这是很合乎逻辑的,MyTrait
的单个实例不可能有相同 属性 的多个实现。在您的解决方案中,您创建了 MyTrait
的多个实例,并且每个实例都获得了 value
的单个稳定实现。