以下作品:
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)
^
答案 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