我有一个特点
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)
}
}这里的问题是,如果不创建一个提取器对象,我就不能使用在该特性中定义的未应用程序。
我想用这个特性覆盖不同对象中的getString方法。
发布于 2021-12-23 12:54:47
您可以使用自我类型来引用自己。
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
}
}就像预期的那样。
运行https://scastie.scala-lang.org/BalmungSan/MnpHz3HGSKSerX5sSoVwaw的代码。
发布于 2021-12-23 06:35:29
我用的一个解决办法是
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://stackoverflow.com/questions/70458471
复制相似问题