功能特性和隐含参数

时间:2013-10-04 19:16:17

标签: scala

以下作品:

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

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

如何使用apply参数键入implicit函数?

我有以下方法:

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)
              ^

1 个答案:

答案 0 :(得分: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