2在不同类中具有相同名称的扩展方法在Scala 3中不起作用? [英] 2 Extension Methods with the same name in different classes do not work in Scala 3?

查看:23
本文介绍了2在不同类中具有相同名称的扩展方法在Scala 3中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方案:

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

上的示例

推荐答案

将评论转换为答案,spec表示两个扩展名都转换为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

Overload resolution已明确改进或扩展,以处理这种正常的重载情况,只有在以后的参数列表中才会区分这种情况。因此,很明显,我们应该意识到经过去垃圾处理的表单已超载。

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

这篇关于2在不同类中具有相同名称的扩展方法在Scala 3中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆