Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a cyclic type definition?

Tags:

scala

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?

like image 976
Thomas Jung Avatar asked Aug 10 '09 07:08

Thomas Jung


2 Answers

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 
  }
like image 23
Yardena Avatar answered Oct 18 '22 14:10

Yardena


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.

like image 123
Walter Chang Avatar answered Oct 18 '22 14:10

Walter Chang