为什么 Scala 在按名称参数重载的情况下的行为与按值参数的情况不同? [英] Why is Scala's behavior in case of overloading with by-name parameters different from the case with by-value parameters?
问题描述
鉴于此 Scala 代码:
Given this Scala code:
object test {
def byval(a: Int) = println("Int")
def byval(a: Long) = println("Long")
def byname(a: => Int) = println("=> Int")
def byname(a: => Long) = println("=> Long")
def main(args: Array[String]) {
byval(5)
byname(5)
}
}
调用 byval(5) 编译正确,但 byname 编译失败:
the call byval(5) compiles correctly, but byname fails to compile:
ambiguous reference to overloaded definition
为什么?我希望在重载方面观察到按值和按名称参数的相同行为……如何修复?
Why? I would expect to observe the same behavior for by-value and by-name parameters with respect to overloading… How can it be fixed?
推荐答案
那是因为 JVM 不支持by-name"参数,所以 Scala 必须以另一种方式实现它.<代码>=>X 实际上编译成一个 Function0[X]
,它擦除为 Function0[Object]
,这使得 Scala 无法区分两个仅通过按名称参数的预期类型.
That's because JVM does not support a "by-name" parameter, so Scala has to implement it in another way. => X
actually compiles to a Function0[X]
, which erases to Function0[Object]
, which makes it impossible for Scala to distinguish two methods that differ only by the expected type of a by-name parameter.
这篇关于为什么 Scala 在按名称参数重载的情况下的行为与按值参数的情况不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!