2016-04-08 148 views
1

在下面的代碼段「需要穩定標識符」,用於枚舉類

val line = ... // a list of String array 
line match { 
    case Seq("Foo", ...) => ... 
    case Seq("Bar", ...) => ... 
    ... 

我上面的代碼改變爲如下:

object Title extends Enumeration { 
    type Title = Value 
    val Foo, Bar, ... = Value 
} 

val line = ... // a list of String array 
line match { 
    case Seq(Title.Foo.toString, ...) => ... 
    case Seq(Title.Bar.toString, ...) => ... 
    ... 

而且,我得到一個錯誤:

stable identifier required, but com.abc.domain.enums.Title.Foo.toString found. 

在case語句中替換字符串的正確方法是什麼?

回答

0

toString是一個函數並且函數不能用於模式匹配。我想Enumeration可能不是你要找的東西。

要匹配的字符串你可以

object Title { 
    val Foo = "Foo" 
    val Bar = "Bar" 
} 

line match { 
    case Seq(Title.Foo, ...) => ??? 
} 
2

函數調用不能用作stable identifier pattern(即它不是stable identifier)。

特別是:

A path is one of the following.

  • The empty path ε (which cannot be written explicitly in user programs).

  • C.this , where C references a class. The path this is taken as a shorthand for C.this where C is the name of the class directly enclosing the reference.

  • p.x where p is a path and x is a stable member of p . Stable members are packages or members introduced by object definitions or by value definitions of non-volatile types.

  • C.super.x or C.super[M].x where C references a class and x references a stable member of the super class or designated parent class M of C . The prefix super is taken as a shorthand for C.super where C is the name of the class directly enclosing the reference.

A stable identifier is a path which ends in an identifier.

因此,你不能在一個模式中使用函數調用像xyz.toString

爲了保持穩定,您可以將其分配到val。如果標識符以小寫字母開頭,你將需要括在反引號('),以避免遮蔽它:

val line = Seq("Foo") // a list of String array 
val FooString = Title.Foo.toString 
val fooLowerCase = Title.Foo.toString 

line match { 
    case Seq(FooString) => ??? 
    // case Seq(fooLowerCase) (no backticks) matches any sequence of 1 element, 
    // assigning it to the "fooLowerCase" identifier local to the case 
    case Seq(`fooLowerCase`) => ??? 
} 

你可以儘管使用衛士:

line match { 
    case Seq(x) if x == Title.Foo.toString => ??? 
} 
+0

感謝您的信息。這個方法對我來說太冗長了。 – TeeKai

+0

@TeeKai它是冗長的,但你根本無法匹配函數調用。我加了一個警衛的例子,看看 –