4

我有以下情况:

case class B(v: String)
case class A(bs: Seq[B])

extension(a: A)
  def doit() = a.bs.map(_.doit()) // here is the exception

extension(b: B)
  def doit() = println("OK: ${b.v}")

这给了我以下编译异常:

value doit is not a member of B.
An extension method was tried, but could not be fully constructed:

    _$1

Scala 3中扩展方法的命名是否有限制

请参阅Scastie上的示例

4

1 回答 1

1

将评论变成答案,规范说两个扩展都被翻译成def extension_doit.

显式调用扩展方法:

-- [E044] Cyclic Error: so.scala:7:45 -----------------------
7 |  extension(a: A) def doit() = a.bs.map(b => extension_doit(b)())
  |                                             ^
  |           Overloaded or recursive method extension_doit needs return type

这与调试原始示例时看到的错误相同:

>>>> StoredError: Overloaded or recursive method extension_doit needs return type
[snip]
-- [E008] Not Found Error: so.scala:7:42 --------------------
7 |  extension(a: A) def doit() = a.bs.map(_.doit())
  |                                        ^^^^^^
  |        value doit is not a member of B.
  |        An extension method was tried, but could not be fully constructed:
  |
  |            _$1

重载解决方案被显式改进或扩展以处理这种可能仅在以后的参数列表中区分的正常重载情况。所以显然我们应该知道去糖的形式是重载的。

Scala 2 也抱怨:

scala> object X { def f(i: Int) = f("") ; def f(s: String) = f(42) }
                                                              ^
       error: overloaded method f needs result type
                                   ^
       error: overloaded method f needs result type
于 2020-09-23T21:48:05.457 回答