Scala 隐式参数的类型查找失败
Scala implicit argument's type finding fail
试图理解这种隐式发现的情况 - finding implicit of an argument's type。我将官方示例复制粘贴到 IDE 中,并将方法名称更改为 mul,如下所示:
class A(val n: Int) {
def mul(other: A) = new A(n + other.n)
}
object A {
implicit def fromInt(n: Int) = new A(n)
}
1 mul (new A(1))
现在它会导致编译错误:
value mul is not a member of Int
我还尝试使用 String 而不是 Int 进行试验,这再次导致编译错误。
你能解释一下我哪里做错了吗?
def +(other: A) =...
和def mul(other: A) =...
的区别在于Int
有+
方法但没有mul
方法
如果方法存在,但传递的参数类型不存在,则编译器将查找隐式转换。包含在隐式范围内的是传递的参数参数的伴随对象。如果发现隐式转换,则评估整个表达式以进行转换。
如果该方法不存在,则伴随对象中的隐式转换不在隐式范围内。它不会被发现,也不会发生转换。
如果您要将 implicit def fromInt(...
移出伴随对象,则会发生 mul()
转换。
试图理解这种隐式发现的情况 - finding implicit of an argument's type。我将官方示例复制粘贴到 IDE 中,并将方法名称更改为 mul,如下所示:
class A(val n: Int) {
def mul(other: A) = new A(n + other.n)
}
object A {
implicit def fromInt(n: Int) = new A(n)
}
1 mul (new A(1))
现在它会导致编译错误:
value mul is not a member of Int
我还尝试使用 String 而不是 Int 进行试验,这再次导致编译错误。
你能解释一下我哪里做错了吗?
def +(other: A) =...
和def mul(other: A) =...
的区别在于Int
有+
方法但没有mul
方法
如果方法存在,但传递的参数类型不存在,则编译器将查找隐式转换。包含在隐式范围内的是传递的参数参数的伴随对象。如果发现隐式转换,则评估整个表达式以进行转换。
如果该方法不存在,则伴随对象中的隐式转换不在隐式范围内。它不会被发现,也不会发生转换。
如果您要将 implicit def fromInt(...
移出伴随对象,则会发生 mul()
转换。