2015-09-04 96 views
1

給定的匹配:模式與私人領域

scala> case class ParentPath(private val x: String) { 
    |  val value = x.dropWhile(_ == '/') 
    | } 

我可以做一個ParentPath

scala> ParentPath("/foo") 
res10: ParentPath = ParentPath(/foo) 

我無法訪問其x(由於private,它出現)。

scala> res10. 
asInstanceOf canEqual copy isInstanceOf productArity productElement productIterator productPrefix toString value 

我可以得到它的value

scala> res10.value 
res11: String = foo 

不過,我更願意返回其value,而不是x在模式匹配:

scala> res10 match { case ParentPath(x) => x} 
res13: String = /foo 

我怎能模式匹配與value,而不是x

scala> ParentPath.unapply(res10) 
res15: Option[String] = Some(/foo) 

我試圖重寫ParentPath#unapply,卻得到了一個編譯時錯誤:

scala> case class ParentPath(private val x: String) { 
    |  val value = "foo" 
    |  override def unapply(p: ParentPath): Option[String] = Some(value) 
    | } 
<console>:15: error: method unapply overrides nothing 
      override def unapply(p: ParentPath): Option[String] = Some(value) 
         ^

回答

3

unapply方法所屬的同伴對象,你不能覆蓋它的情況下類,反正。對於普通班級來說,這將起作用。 ,如果您只是使用具有相同簽名的unapply方法的不同名稱的對象。

class ParentPath(private val x: String) { 
    val value = "foo" 
} 

object ParentPath { 
    def unapply(p: ParentPath): Option[String] = Some(p.value) 
} 

scala> new ParentPath("/foo") match { case ParentPath(x) => x } 
res1: String = foo 
+0

'無論如何你都無法重寫它,因爲'哦,所以它是'final'呢? –

+0

它與案例類同伴嘗試生成的'unapply'方法衝突。 –