Creating a new distinct type isomorphic to an existing one

I would like to define a type that is isomorphic to, say, Int. I read that opaque type can be used to this end. However, existing operators don’t seem to be available on a new type defined in this way.

The following code does not compile (value + is not a member of types.Int2s.Int2).

object Int2s {
  opaque type Int2 = Int
}

import Int2s._

def double(n: Int2): Int2 = n + n

Is there a way to make the operators for Int available for Int2 as well?

P.S.: Oddly, normal methods do seem to be available on opaque types.

This page talks about it (also shows examples that don’t work, which seem to be intended), I think with the opaque approach you would have to write extension methods as shown in the examples. Not sure what is a better approach, hope someone else can point it out.

1 Like

Keep in mind, the point of opaque types is that they are opaque: calling code can’t see “into” them. The fact that Int2 is actually an Int under the surface is intentionally hidden from pretty much all other code. So it makes sense that you can’t use + (indeed, that’s by design): callers don’t know that it is actually Int, so they don’t know that there is a + method.

In other words, by using opaque, all traces of its Int-ness become internal implementation details. You need to explicitly spell out the desired methods of Int2 – it doesn’t inherit anything from Int. (At least, not in its public interface.)

2 Likes

Nevermind, I got misled by my IDE.