[英]Function trait and implicit parameters
以下作品:
object X extends (Int => String => Long) {
def apply(x:Int):String => Long = ???
}
我怎么能用implicit
参数键入apply
函数?
我有以下方法:
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)
^
我唯一想到的是:
object X {
def apply(i: Int)(implicit y: String): Long = ???
implicit def xToFun(x: X.type)(implicit y: String): Int => Long = x(_)
}
隐式转换将允许您在需要Int => Long
地方使用X
,并且在应用该转换时将解析隐式String
参数(而不是在实际调用X.apply
时):
val fun: Int => Long = X //error, no implicit String in scope
implicit val s = "fuu"
val fun: Int => Long = X //OK
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.