Top level opaque type with same underlying type and identical extensions methods

Viewed 148

I ran into an issue when defining opaque types with identical underlying types and extension methods, e.g.:

opaque type HandleA = Int

object HandleA:

  def apply(value: Int): HandleA = value

extension (handle: HandleA) @targetName("HandleA_value") def value: Int = handle

opaque type HandleB = Int

object HandleB:

  def apply(value: Int): HandleB = value

extension (handle: HandleB) @targetName("HandleB_value") def value: Int = handle

When the two definitions resided in the same file, the code compiled, but when defined in two separate files, the code did not compile with the following error:

value is already defined as method value in ...

Is there a way to create these definitions at the same level in separate files somehow?

I tried wrapping the definitions in objects in two separate files and making them available at the top-level of the package by exporting them

// HandleA.scala

object HandleAWrap:
  opaque type HandleA = Int

  object HandleA:

    def apply(value: Int): HandleA = value

    extension (handle: HandleA) @targetName("HandleA_value") def value: Int = handle

// HandleB.scala

object HandleBWrap:
  opaque type HandleB = Int

  object HandleB:

    def apply(value: Int): HandleB = value

    extension (handle: HandleB) @targetName("HandleB_value") def value: Int = handle

// Lib.scala

export HandleAWrap.*
export HandleBWrap.*

But doing this I got a different compilation error along the lines of:

cyclic reference via <import>

due to the usage of @targetName to avoid name clashes.

0 Answers
Related