Why do I get "expected class or object definition" when defining a type in scala?

gotch4 picture gotch4 · Mar 13, 2015 · Viewed 8.2k times · Source

If I write something like this (to define Slick tables as per docs):

type UserIdentity = (String, String)
class UserIdentity(tag: Tag){
...
}

I get a compile error: "expected class or object definition" pointing to the type declaration. Why?

Answer

Dan Simon picture Dan Simon · Mar 13, 2015

You can't define type aliases outside of a class, trait, or object definition.

If you want a type alias available at the package level (so you don't have to explicitly import it), the easiest way around this to define a package object, which has the same name as a package and allows you to define anything inside of it, including type aliases.

So if you have a foo.barpackage and you wish to add a type alias, do this:

package foo

package object bar {
  type UserIdentity = (String, String)
}

//in another file
package foo.bar
val x: UserIdentity = ...