2013-09-01 77 views
1

实现一个循环枚举下面是我想用尝试在斯卡拉

trait CircularEnumeration extends Enumeration { 

    class CircularVal extends Val { 
     def next(): Value = { 
     apply((id + 1) % values.size) 
     } 
    } 

    protected override final def Value: CircularVal = new CircularVal; 

    /////////////////////////////////////////////////////////////////////////// 

    def nextValue(value: Value) = { 
     //first way 
     val nextIndex = values.toSeq.indexOf(value) + 1; 
     val value_nomath = if (nextIndex >= values.size) { 
     values.toSeq(0); 
     } 
     else { 
     values.toSeq(nextIndex); 
     } 

     //second way 
     val value_withmath = this((value.id + 1) % values.size); 

     assert(value_nomath == value_withmath); 

     value_withmath; 
    } 
} 

你可以看到,我已经尝试了两种方式的特点,并且都失败了。 在首先进行的用法是这样的:
MyEnumeration(index).next
这将返回我的下一个值此枚举的

在第二的用法是这样的:
MyEnumeration.nextValue(MyEnumeration(index))
并再次这将返回下一个值

但在这两种情况下,我有哪些类型是哪个问题。由于性状内Value实际上是CircularEnumeration.Value而具有这种特质塔ValueMyEnumeration.Value

任何想法里面的类?

回答

2

我相信我能得到它,进行如下改变工作 - 修改nextValue的返回类型:

def nextValue(value: Value): CircularEnumeration.this.Value = { 

最后一行(返回值):

value_withmath.asInstanceOf[CircularEnumeration.this.Value] 

然后,定义MyEnumeration为:

scala> object MyEnumeration extends CircularEnumeration { 
    |  type MyEnumeration = Value 
    |  val Zero, One, Two, Three, Four = Value 
    | } 
defined module MyEnumeration 

我们得到:

scala> MyEnumeration.nextValue(MyEnumeration(3)) 
res0: MyEnumeration.Value = Four 

scala> MyEnumeration.nextValue(MyEnumeration(4)) 
res1: MyEnumeration.Value = Zero 
+0

这产生了不同:'CircularEnumeration.this.Value'。非常感谢,它按预期工作:) –