可以覆盖scala特征中的私有val

时间:2015-04-19 18:41:21

标签: scala

我必须测试包含私有val的特征,但是这个val需要覆盖测试建议。

trait A {
  private val someVariable = 0
}

测试类

@RunWith(classOf[JUnitRunner]) class ATest extends FunSuite {
  val a = new A{
    override private val someVariable = 1 
  }

  test("test of someVariable ){
    assert(a.someVariable == 1) //I know that I can't print private variable in this way, but it is just for showing what I need.
  }

} 

这里有一些方法可以覆盖这个变量吗? 感谢

2 个答案:

答案 0 :(得分:1)

特征初始化器还需要设置该字段,因此您可以利用该公共合成设置器:

scala> :pa -raw
// Entering paste mode (ctrl-D to finish)

package XX { trait X { private val x = 42 ; def test = x * 2 } }

// Exiting paste mode, now interpreting.


scala> (new XX.X {}).test
res0: Int = 84

scala> val v = new XX.X {}
v: XX.X = $anon$1@3cd1f1c8

scala> classOf[XX.X].getDeclaredMethod("XX$X$_setter_$XX$X$$x_$eq", classOf[Int])
res1: java.lang.reflect.Method = public abstract void XX.X.XX$X$_setter_$XX$X$$x_$eq(int)

scala> res1.invoke(v, 3: Integer)
res2: Object = null

scala> v.test
res3: Int = 6

反射皮肤猫的方法不止一种。

答案 1 :(得分:0)

我将我的特质修改为

trait A {
  private[package] val someVariable = 0
}

现在它正在运作。