Why does scala evaluate a type alias when it has a line break and no equals sign?

102 Views Asked by At

I notice when declaring a type alias in the REPL, a line break causes a statement to succeed:

this works:

scala> type a
     | 3 == 3
defined type alias a
res32: Boolean = true

This does not:

scala> type a 3 == 3              ^
       error: `=`, `>:`, or `<:` expected
1

There are 1 best solutions below

3
som-snytt On BEST ANSWER

It's legal to have an abstract type as shown.

The REPL is in a special parsing mode where it knows if the current line is a complete syntax production or if more input is required, so that's why it goes to a second line, even though technically it should just accept type a.

scala> object X { type a }
defined object X

scala> object X { def x: Int }
                      ^
       error: only traits and abstract classes can have declared but undefined members

scala> type a
     | 42
defined type alias a
res0: Int = 42

scala> def x: Int
     | 42
           ^
       error: only traits and abstract classes can have declared but undefined members

The REPL doesn't import the abstract typedef into the current expression because it knows it is abstract.

The type maybe not be very useful, but it is a thing:

scala> object X { type a }
defined object X

scala> val x: X.a = null.asInstanceOf[X.a]
x: X.a = null

scala> def x: X.a = ???
x: X.a

scala> def x: X.a = null
                    ^
       error: type mismatch;
        found   : Null(null)
        required: X.a