首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Scala 3中不透明类型的删除后的相同类型

Scala 3中不透明类型的删除后的相同类型
EN

Stack Overflow用户
提问于 2022-06-26 10:38:48
回答 1查看 41关注 0票数 0

我想要定义两个不透明类型别名,它们是用相同的底层类型double实现的。我还想在同名别名上定义两个扩展方法。以下是汇编:

代码语言:javascript
复制
object MyMath1:
  object Logarithms1:
    opaque type Logarithm1 = Double
    extension (l1: Logarithm1) def foo: Unit = ()
  object Logarithms2:
    opaque type Logarithm2 = Double
    extension (l2: Logarithm2) def foo: Unit = ()
  import Logarithms1.Logarithm1
  import Logarithms2.Logarithm2

但是,我希望这些扩展方法在定义不透明类型别名的范围之外定义,即在MyMath对象中:

代码语言:javascript
复制
object MyMath2:
  object Logarithms1:
    opaque type Logarithm1 = Double
  object Logarithms2:
    opaque type Logarithm2 = Double
  import Logarithms1.Logarithm1
  import Logarithms2.Logarithm2
  extension (l1: Logarithm1) def foo: Unit = ()
  extension (l2: Logarithm2) def foo: Unit = ()

这会导致以下编译器错误:

代码语言:javascript
复制
Double definition:
def foo(l1: MyMath.Logarithms1.Logarithm1): Unit in object MyMath at line 52 and
def foo(l2: MyMath.Logarithms2.Logarithm2): Unit in object MyMath at line 53
have the same type after erasure.

Consider adding a @targetName annotation to one of the conflicting definitions
for disambiguation.

添加@targetName注释确实解决了这些问题。

我的问题是:为什么第一个代码段编译而第二个代码段不编译?当然,在第一个片段中,两个方法在擦除后也具有相同的类型。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-05 11:59:01

编译后的Java类不能有两个签名(类型擦除后的名称+参数类型)重合的方法。

在第一个片段中,方法在不同的对象中声明,因此被编译成不同类的方法,因此没有冲突。

在第二种情况下,这两种方法都将呈现为同一类的方法。由于已编译类中的基础类型替换了不透明类型,因此存在冲突(同名foo,相同的擦除参数类型double)。

应用@targetName注释可以在编译后的类中重命名一个或两个方法,从而消除歧义。见与覆盖的关系

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72760829

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档