我想要定义两个不透明类型别名,它们是用相同的底层类型double实现的。我还想在同名别名上定义两个扩展方法。以下是汇编:
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对象中:
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 = ()这会导致以下编译器错误:
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注释确实解决了这些问题。
我的问题是:为什么第一个代码段编译而第二个代码段不编译?当然,在第一个片段中,两个方法在擦除后也具有相同的类型。
发布于 2022-07-05 11:59:01
编译后的Java类不能有两个签名(类型擦除后的名称+参数类型)重合的方法。
在第一个片段中,方法在不同的对象中声明,因此被编译成不同类的方法,因此没有冲突。
在第二种情况下,这两种方法都将呈现为同一类的方法。由于已编译类中的基础类型替换了不透明类型,因此存在冲突(同名foo,相同的擦除参数类型double)。
应用@targetName注释可以在编译后的类中重命名一个或两个方法,从而消除歧义。见与覆盖的关系。
https://stackoverflow.com/questions/72760829
复制相似问题