如何在具有隐式参数

时间:2015-12-09 06:48:15

标签: scala

如何为这些类调用XYZ.doSomething方法:

XYZ.scala

object XYZ {

  private def doSomething(i : Int)(implicit s: String): String {
    s + i.toString
  }
}

XYZTest.scala

class XYZTest extends FunSpec with PrivateMethodTester {
  describe("SomeTest") {
    it("Can't find a private method named: doSomething :( ") {
      implicit lazy val someStr: String = "sahil"
      val doSomething = PrivateMethod[String]('doSomething)
      val myStr = XYZ invokePrivate doSomething(1)
      assert(myStr == "sahil1")
    }
  }
  describe("SomeTest") {
    it("This doesn't even compile :( ") {
      val doSomething = PrivateMethod[String]('doSomething)
      val myStr = XYZ invokePrivate doSomething(1)("sahil")
      assert(myStr == "sahil1")
    }
  }
}

1 个答案:

答案 0 :(得分:4)

正确答案是:

object XYZ {

  private def doSomething(i : Int)(implicit s: String): String = {
    s + i.toString
  }
}

class XYZTest extends FunSpec with PrivateMethodTester {
  describe("SomeTest") {
    it("Can't find a private method named: doSomething :( ") {
      implicit lazy val someStr: String = "sahil"
      val doSomething = PrivateMethod[String]('doSomething)
      val myStr = XYZ invokePrivate doSomething(1, someStr)
      assert(myStr == "sahil1")
    }
  }
}

invokePrivate方法的简要说明显示它不支持implicits,但看起来它将currying参数列表视为参数的一般序列

def invokePrivate[T](invocation : PrivateMethodTester.this.Invocation[T])

其中args是序列:

final class Invocation[T](val methodName : scala.Symbol, val args : scala.Any*)