Why doesn't scala allow global `type` definitions?

After all traits and class are types right… And if opaque types land and people start replacing their value classes, wouldn’t the lack of this feature make it more cumbersome.

See https://github.com/scala/scala-dev/issues/441

1 Like

That’s my concern too.

But to answer your general question, the reason scala doesn’t allow global type definitions is because that code must live somewhere, and packages are open, and the compiler must work in the face of separate compilation. So the closest you can get is package objects.

This is quite understandable for most definitions. But don’t type aliases disappear completely at runtime?

For example:

type X = Int

Does X exist at runtime?

It doesn’t exist at runtime, but it has to be stored somewhere in a file. And the only kind of files the Scala JVM backend can read and write are class files.

1 Like

Stuff that doesn’t exist at run time, doesn’t need to be in any Java class file. But more importantly, just because a lot of stuff ends up in the package object class file doesn’t mean, it all has to come from the same source file. I still use implicit defs with a separate class, rather than implicit classes, quite a bit, because that allows me to put the extension methods into a separate file.

Exactly. That’s what annoys me the most about package objects. It keeps me from properly splitting the code into separate parts that still need to come together in a single import statement.

1 Like

It has to be preserved in bytecode for separate compilation. When I compile my code against your type-alias-using library, I need to see that type alias definition. And all you’ve given me is your-library.jar.

So if A.scala and B.scala define package object p what happens when you compile first A.scala and then B.scala?

Just for clarity, I’m with you on the downsides of this limitation. I’m quietly optimistic that Java’s push against split packages/modules will eventually lead to these issues being solved.

I think we could get it to work. If I define a top-level type Foo, the compiler could generate a Foo.class with a private dummy class, and use the pickling information to keep track of the fact that it’s really a type definition.


Hmm, I think we discussed this in a SIP meeting not a lot of time ago and we agreed that it would be great to allow top-level type aliases so that the boilerplate of using opaque types wouldn’t be so “high”.


Cool. I think Martin had some thoughts along the same lines for extension methods, which would be wonderful to be able to define top-level.