gpt4 book ai didi

scala - 函数特征和隐式参数

转载 作者:行者123 更新时间:2023-12-01 02:22:32 25 4
gpt4 key购买 nike

以下工作:

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

最佳答案

我唯一想到的是:

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

关于scala - 函数特征和隐式参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19189085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com