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)
^
'無論如何你都無法重寫它,因爲'哦,所以它是'final'呢? –
它與案例類同伴嘗試生成的'unapply'方法衝突。 –