我有一個特點
trait A {
def doSomething(a: Seq[Int]): Seq[String] = {
a.map {
case AA(s) => s // want to use unapply defined in trait (this(AA) not allowed)
case _ => "idc"
}
}
def unapply(a: Int): Option[String] = getString(a)
def getString(a: Int): Option[String] = {
a match {
case 1 => Some("one")
case 2 => Some("two")
case _ => None
}
}
}
object AA extends A
object AA2 extends A {
override def getString(a: Int): Option[String] = {
super.getString(a).orElse{
a match {
case 3 => Some("three")
case 4 => Some("four")
case _ => None
}
}
}
}
object MyClass {
def main(args: Array[String]) {
println(AA.doSomething(Seq(1,2,3,4,5))); // Output: List(one, two, idc, idc, idc)
println(AA2.doSomething(Seq(1,2,3,4,5))); // Expect Output: List(one, two, three, four, idc) but get List(one, two, idc, idc, idc)
}
}
這里的問題是我不能在不創建提取器物件的情況下使用特征中定義的 unapply 。
我想使用此特征覆寫不同物件中的 getString 方法。
uj5u.com熱心網友回復:
您可以使用 self 型別來參考自己。
trait A { self =>
final def doSomething(a: Seq[Int]): Seq[String] =
a.map {
case self(s) => s
case _ => "idc"
}
final def unapply(a: Int): Option[String] =
getString(a)
def getString(a: Int): Option[String] =
a match {
case 1 => Some("one")
case 2 => Some("two")
case _ => None
}
}
這按預期作業。
代碼在這里運行。
uj5u.com熱心網友回復:
我使用的一種解決方案是
trait A {
def doSomething(a: Seq[Int]): Seq[String] = {
a.map {
case Extractor(s) => s
case _ => "idc"
}
}
object Extractor {
def unapply(a: Int): Option[String] = getString(a)
}
def getString(a: Int): Option[String] = {
a match {
case 1 => Some("one")
case 2 => Some("two")
case _ => None
}
}
}
object AA extends A
object AA2 extends A {
override def getString(a: Int): Option[String] = {
super.getString(a).orElse{
a match {
case 3 => Some("three")
case 4 => Some("four")
case _ => None
}
}
}
}
object MyClass {
def main(args: Array[String]) {
println(AA.doSomething(Seq(1,2,3,4,5))); // Output: List(one, two, idc, idc, idc)
println(AA2.doSomething(Seq(1,2,3,4,5))); // Output: List(one, two, three, four, idc)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/393194.html
