简体   繁体   中英

2 Extension Methods with the same name in different classes do not work in Scala 3?

I have the following scenario:

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}")

This gives me the following exception on compilation:

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

    _$1

Are there restrictions in the naming of extension methods in Scala 3 ?

See the example here on Scastie

Turning the comment into an answer, the spec says both extensions are translated to def extension_doit .

Calling the extension method explicitly:

-- [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

This is the same error seen with debug of the original example:

>>>> 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

Overload resolution was explicitly improved or extended to handle this normal case of overloads which may be differentiated only in later parameter lists. So apparently we are supposed to be aware that the desugared form is overloaded.

Scala 2 also complains:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM