Scala 函数特性与隐参数
以下工作:Scala 函数特性与隐参数,scala,Scala,以下工作: object X extends (Int => String => Long) { def apply(x:Int):String => Long = ??? } 如何键入带有隐式参数的应用函数 我有以下方法: def apply(x:Int)(implicit y:String):Long = ??? 如何描述函数类型 object X extends <functionType> { def apply(x:Int)(implicit
object X extends (Int => String => Long) {
def apply(x:Int):String => Long = ???
}
如何键入带有隐式
参数的应用
函数
我有以下方法:
def apply(x:Int)(implicit y:String):Long = ???
如何描述函数类型
object X extends <functionType> {
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
时):
你确实让我深思了,谢谢!
object X {
def apply(i: Int)(implicit y: String): Long = ???
implicit def xToFun(x: X.type)(implicit y: String): Int => Long = x(_)
}
val fun: Int => Long = X //error, no implicit String in scope
implicit val s = "fuu"
val fun: Int => Long = X //OK