2011-06-28 87 views
13

對象L1以下的作品。我可以通過傳入可變參數「創建」L1,這很好,但我希望能夠使用相同的語法分配到L1。不幸的是,我在這裏完成的方式需要在L1內嵌套Array的醜陋語法。斯卡拉 - 可以不申請返回可變參數嗎?

object L1 { 
    def apply(stuff: String*) = stuff.mkString(",") 
    def unapply(s: String) = Some(s.split(",")) 
} 
val x1 = L1("1", "2", "3") 
val L1(Array(a, b, c)) = x1 
println("a=%s, b=%s, c=%s".format(a,b,c)) 

我試圖在什麼似乎是一個明顯的方式做到這一點,因爲在L2如下:

object L2 { 
    def apply(stuff: String*) = stuff.mkString(",") 
    def unapply(s: String) = Some(s.split(","):_*) 
} 
val x2 = L2("4", "5", "6") 
val L2(d,e,f) = x2 
println("d=%s, e=%s, f=%s".format(d,e,f)) 

但是,這給了錯誤:

error: no `: _*' annotation allowed here 
(such annotations are only allowed in arguments to *-parameters)`. 

是否有可能爲unapply到以這種方式使用可變參數?

回答

21

我認爲你想要的是不適用Seq。傑西Eichar有一個很好的寫在unapplySeq

scala> object L2 { 
    |  def unapplySeq(s: String) : Option[List[String]] = Some(s.split(",").toList) 
    |  def apply(stuff: String*) = stuff.mkString(",") 
    | } 
defined module L2 

scala> val x2 = L2("4", "5", "6") 
x2: String = 4,5,6 

scala> val L2(d,e,f) = x2 
d: String = 4 
e: String = 5 
f: String = 6 
+0

完美!謝謝! – dhg