强制访问def

时间:2011-09-30 10:43:51

标签: scala overloading shadowing

考虑

object A {
  def m(i: Int) = i
  val m = (i: Int) => i * 2
}

一个得到

scala> A.m(2)
<console>: error: ambiguous reference to overloaded definition,
both value m in object A of type => (Int) => Int
and  method m in object A of type (i: Int)Int
match argument types (Int)
       A.m(2)
         ^

可以使用

访问val
scala> val fun = A.m
fun: (Int) => Int = <function1>

scala> fun(2)
res: Int = 4

scala> A.m.apply(2)
res: Int = 4

但是如何访问def

1 个答案:

答案 0 :(得分:11)

这是完全垃圾(请不要在家里这样做),但你可以assigning A to a variable of structural type, that has only the first m来做。

val x : { def m(i:Int):Int } = A
x.m(10)