2009-08-10 145 views
6

這不是一個有效的類型定義:如何定義循環類型定義?

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

可這在Scala中表達?

回答

4

不,它不能。

在Scala語言規範版本2.7的40頁:

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.

0

似乎在斯卡拉2.8,這可能是 「固定」:

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

+0

它不會與目前的每日構建工作。 歡迎來到Scala 2.8.0.r18457-b20090810020144(Java HotSpot TM Client V M,Java 1.6.0_12)。 輸入表達式來評估它們。 類型:help獲取更多信息。 scala> class A { |鍵入Addable = {def +(subject:Addable)} | } :5:錯誤:涉及方法的非法循環引用+ type Addable = {def +(subject:Addable)} 至少錯誤消息已更改:-)。 – 2009-08-10 07:52:02

+0

您是否嘗試過上述文章底部提到的實驗命令行選項? – skaffman 2009-08-10 08:42:28

+0

相同結果:scala -Yrecursion 10 – 2009-08-10 09:08:23

1

這是我在圖書館做了我寫的,HTH:

trait Addable { 
    type AddableType <: Addable 
    def + (subject: AddableType): AddableType 
    } 
    trait Rational extends Addable { 
    type AddableType = Rational 
    override def + (subject: Rational): Rational 
    } 
+0

定義必須是結構類型,因爲下劃線類無法更改(如Int,Long)。 – 2009-08-12 05:11:00

+2

嗯,也許你可以定義一個視圖(隱式def)將這些類轉換爲可添加? – Yardena 2009-08-12 15:41:38