gotch4
gotch4

Reputation: 13299

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

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?

Upvotes: 13

Views: 11162

Answers (1)

Dan Simon
Dan Simon

Reputation: 13137

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 = ...

Upvotes: 23

Related Questions