如何围绕scalatest';s";它";关键词?

如何围绕scalatest';s";它";关键词?,scala,scalatest,scalactic,Scala,Scalatest,Scalactic,我正试图围绕的it关键字构建一个包装器。然而,这个解决方案似乎并没有达到预期的效果。此外,它甚至不编译: trait MyFunSpec extends FunSpec { private val _it: FunSpec.this.ItWord = it protected def it(specText: String, testTags: org.scalatest.Tag*) // ...do something extra here... (testFun:

我正试图围绕的
it
关键字构建一个包装器。然而,这个解决方案似乎并没有达到预期的效果。此外,它甚至不编译:

trait MyFunSpec extends FunSpec {

  private val _it: FunSpec.this.ItWord = it

  protected def it(specText: String, testTags: org.scalatest.Tag*)
    // ...do something extra here...
    (testFun: => Any /* Assertion */)(implicit pos: Position): Unit = {
    _it(specText, testTags: _*)(testFun)(pos)
    // ...do something extra here...
  }
}
编译此代码后收到的错误消息如下:

[error] MyFunSpec.scala: ambiguous reference to overloaded definition,
[error] both method it in trait MyFunSpec of type (specText: String, testTags:
  org.scalatest.Tag*)(testFun: => Any)(implicit pos:
  org.scalactic.source.Position)Unit
[error] and value it in trait FunSpecLike of type => FunSpecSpec.this.ItWord
[error] match argument types (String)
请注意,主要思想是方法的名称仍然是
it
,因此将其重命名为类似
alternativeIt
的名称并不是一个令人满意的解决方案

有什么建议吗,我做错了什么?任何解决方案都将不胜感激!谢谢

试试这个:

trait MyFunSpec extends FunSpec {
  override protected val it = new ItWord {
    override def apply(specText: String,testTags: org.scalatest.Tag*)(testFun: => Any)(implicit pos: org.scalactic.source.Position): Unit = {
      println("Before")
      super.apply(specText, testTags:_*)(testFun)(pos)
      println("After")
    }
  }
}

用几句话来解释你的解决方案会很好。OP还询问了他们自己的代码出了什么问题。当你试图将它别名为_it时,编译器会感到困惑,因为如果它在FunSpecLike中有一个定义,而在MyTrait中有另一个定义(因此它被重载)。其次,为了真正覆盖它,您应该实际覆盖val it=new ItWord{…}。在这个匿名类中,super引用了FunSpec中旧的ItWord实现。