4

以下作品:

object X extends (Int => String => Long) {

  def apply(x:Int):String => Long = ???
}

我怎样才能输入一个applyimplicit参数的函数?

我有以下方法:

def apply(x:Int)(implicit y:String):Long = ???

如何描述函数类型?

object X extends <functionType> {
  def apply(x:Int)(implicit y:String):Long = ???
}

更新

我可以这样定义:

object X extends (Int => String => Long) { 

  def apply(x:Int):(String => Long) = ???
  def apply(x:Int)(implicit y:String):Long = ???; 
}

但随后调用它不起作用:

error: ambiguous reference to overloaded definition,
both method apply in object X of type (x: Int)(implicit y: String)Long
and  method apply in object X of type (x: Int)String => Long
match argument types (Int)
              X(3)
              ^
4

1 回答 1

3

我唯一想到的就是这个:

object X {
  def apply(i: Int)(implicit y: String): Long = ???

  implicit def xToFun(x: X.type)(implicit y: String): Int => Long = x(_)
}

隐式转换将允许您在需要的X任何地方使用Int => Long,并且隐式String参数将在应用该转换时解析(而不是在X.apply实际调用时):

val fun: Int => Long = X //error, no implicit String in scope

implicit val s = "fuu"
val fun: Int => Long = X //OK
于 2013-10-04T19:29:53.883 回答