gpt4 book ai didi

scala - 不同类型List的通用unapply方法

转载 作者:行者123 更新时间:2023-12-03 03:36:02 27 4
gpt4 key购买 nike

有没有办法用泛型来泛化这段代码?

object ListInt {
def unapply(o: Any): Option[List[Int]] = o match {
case lst: List[_] if(lst.forall(_.isInstanceOf[Int])) =>
Some(lst.asInstanceOf[List[Int]])
case _ => None
}
}
object ListDouble {
def unapply(o: Any): Option[List[Double]] = o match {
case lst: List[_] if(lst.forall(_.isInstanceOf[Double])) =>
Some(lst.asInstanceOf[List[Double]])
case _ => None
}
}
object ListString {
def unapply(o: Any): Option[List[String]] = o match {
case lst: List[_] if(lst.forall(_.isInstanceOf[String])) =>
Some(lst.asInstanceOf[List[String]])
case _ => None
}
}

val o: Any = List("a", "b", "c")
o match {
case ListInt(lst) => println(lst.sum)
case ListDouble(lst) => println(lst.product)
case ListString(lst) => println(lst.mkString("(", ", ", ")"))
case _ => println("no match")
}

最佳答案

abstract class ListExtractor[A](implicit ct: reflect.ClassTag[A]) {
def unapply(o: Any): Option[List[A]] = o match {
case lst: List[_] if (lst.forall(ct.unapply(_).isDefined)) =>
Some(lst.asInstanceOf[List[A]])
case _ => None
}
}

object ListInt extends ListExtractor[Int ]
object ListString extends ListExtractor[String]

val o: Any = List("a", "b", "c")
o match {
case ListInt (lst) => println(lst.sum)
case ListString(lst) => println(lst.mkString("(", ", ", ")"))
case _ => println("no match")
}

关于scala - 不同类型List的通用unapply方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16885199/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com