2013-04-01 38 views
2

在使用java多年後我正在嘗試進入scala。 可以說我有一個簡單枚舉這樣在scala中使用參數和方法枚舉

public enum Foo{ 
    Example("test", false), 
    Another("other", true); 

    private String s; 
    private boolean b; 

    private Foo(String s, boolean b){ 
    this.s = s; 
    this.b = b; 
    } 

    public String getSomething(){ 
    return this.s; 
    } 

    public boolean isSomething(){ 
    return this.b; 
    } 
} 

與實況和計算器我得到儘可能一些幫助:

object Foo extends Enumeration 
{ 
    type Foo = Value 
    val Example, Another = Value 

    def isSomething(f : Foo) : Boolean = f match { 
    case Example => false 
    case Another => true 
    } 

    def getSomething(f : Foo) : String = f match { 
    case Example => "test" 
    case Another => "other" 
    } 
} 

但我不喜歡這樣的幾個原因。 首先,值遍佈各種方法,每次添加新條目時都需要更改它們。 其次,如果我想調用一個函數,它將以Foo.getSomething(Another)的形式或類似的東西,我覺得很奇怪,我寧願另一個.getSomething。 我希望將這些改爲更優雅的建議。

+2

[scala:add m方法到枚舉](http://stackoverflow.com/questions/12345823/scala-add-methods-to-an-enum) –

回答

7

是否需要使用Enumeration

你可以使用sealed abstract classcase object

sealed abstract class Foo(val something: String, val isSomething: Boolean) 

case object Example extends Foo ("test", false) 
case object Another extends Foo ("other", true) 

你會得到一個警告,如果你會忘記一些Foo實例:

scala> def test1(f: Foo) = f match { 
    | case Example => f.isSomething 
    | } 
<console>:1: warning: match may not be exhaustive. 
It would fail on the following input: Another 
     def test1(f: Foo) = f match { 

您還可以添加方法,您列舉實例:

implicit class FooHelper(f: Foo.Value) { 
    def isSomething(): Boolean = Foo.isSomething(f) 
} 

scala> Foo.Example.isSomething 
res0: Boolean = false 
+0

不,它沒有必要使用枚舉。我會考慮這些密封的case類,謝謝答案=) – Nozdrum

+0

@sourcedelica,'FooHelper'用於'object Foo extends Enumeration',而不是'sealed abstract class Foo'。我的回答中直接調用了'f.isSomething'。 – senia

+0

啊 - 對不起,我錯過了。 – sourcedelica