Possible simplification for opaque types

I just created some opaque types:

opaque type FlightName   = String
opaque type AircraftType = String
opaque type AirportCode  = String

object FlightName   { def apply(s: String): FlightName   = s }
object AircraftType { def apply(s: String): AircraftType = s }
object AirportCode  { def apply(s: String): AirportCode  = s }

It’s a nice concept, but those objects with apply methods seem like unnecessary boilerplate. Could they be automatically generated by the compiler?

Take a look to this and linked discussions.

TL;DR; maybe a library will but the language team is pretty convinced that the best is not to do it.

Thanks for pointing me to that previous discussion. It seems to me that they are discussing more complicated uses than my trivial examples. In my examples, the opaque types would be useless without the apply methods in the companion objects, and those apply methods are trivial boilerplate. So why not just eliminate the boilerplate? Not a big deal either way, of course.

Yeah, that is the same point many people make.

Also, wait until you need to do things with those new types, you need to start adding extension methods or a simple get or toString that returns the original value.

Again, the “problem” is that for the language authors, opaque types are more powerful than plain new types, which allow more things. For example, if you need validations.

So for now, you need to live with the boilerplate, and probably in future libraries like scala-newtype will probably provide a simpler way.

You could use methods to make it a little shorter. def FlightName(s: String): FlightName = s.

1 Like

OK, this is nitpicking, but why can’t I write

object Foo: def apply(s: String): Foo = s

instead of

object Foo { def apply(s: String): Foo = s }


object Foo:
  def apply(s: String): Foo = s

Ditto for enums.

If it’s a one-liner, I like to see it on one line if it fits – without the braces.