7

This is not a valid type definition:

scala>  type Addable = { def +(subject: Addable) }
<console>:4: error: illegal cyclic reference involving type Addable
        type Addable = { def +(subject: Addable) }

Can this be expressed in scala?

Thomas Jung
  • 32,428
  • 9
  • 84
  • 114

3 Answers3

5

No, it can't.

On page 40 of The Scala Language Specification Version 2.7:

However, it is a static error if a type alias refers recursively to the defined type constructor itself. That is, the type T in a type alias type t[tps] = T may not refer directly or indirectly to the name t.

Walter Chang
  • 11,547
  • 2
  • 47
  • 36
1

Here's what I did in a library I wrote, HTH:

  trait Addable {
    type AddableType <: Addable
    def + (subject: AddableType): AddableType
  }
  trait Rational extends Addable {
    type AddableType = Rational
    override def + (subject: Rational): Rational 
  }
Yardena
  • 2,837
  • 20
  • 17
0

It seems this may be "fixed" in Scala 2.8:

http://lampsvn.epfl.ch/trac/scala/ticket/1291

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • It does not work with the current nightly build. Welcome to Scala version 2.8.0.r18457-b20090810020144 (Java HotSpot(TM) Client V M, Java 1.6.0_12). Type in expressions to have them evaluated. Type :help for more information. scala> class A{ | type Addable = { def +(subject: Addable) } | } :5: error: illegal cyclic reference involving method + type Addable = { def +(subject: Addable) } At least the error message changed :-). – Thomas Jung Aug 10 '09 at 07:52
  • Did you try the experimental command line option mentioned at the bottom of the above article? – skaffman Aug 10 '09 at 08:42
  • Same result with: scala -Yrecursion 10 – Thomas Jung Aug 10 '09 at 09:08