【问题标题】:Force accessing of a def强制访问 def
【发布时间】:2011-11-28 09:13:13
【问题描述】:

考虑

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

【问题讨论】:

    标签: scala overloading shadowing


    【解决方案1】:

    这完全是垃圾(请不要在家里这样做),但您可以通过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)
    

    【讨论】:

    • 绝招!顺便说一句,只是铸造也有效: A.asInstanceOf[{def m(i:Int):Int}].m(10)
    • @Philippe:那里不需要asInstanceOf(A: {def m(i:Int):Int}).m(10)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    相关资源
    最近更新 更多