scala groupby不同的类

时间:2015-07-05 12:26:56

标签: scala

我有一个list,可能包含三种不同类型的类,并且都来自E类,例如A extends EB extends EC extends E 。我需要识别list中的每个元素并相应地进行一些计算。 (list将来可能会包含更多的E子类。)

我更喜欢使用mappartitiongroupBy,而不仅仅是if,但我现在更加困惑。因为我对Scala很新,如果有人可以分享一些想法?谢谢!

val list = //some codes to get the list//
list.groupby{
  _.getClass  //so in this line, is it possible to call the calculation method accordingly?
}

trait A extends E {
  def calA = {...}
}

trait B {
  def calB = {...}
}
trait C {
  def calC = {...}
}

1 个答案:

答案 0 :(得分:2)

您可以使用模式匹配处理不同的类:

val list = List(1, "s", "t")
list map {
  case a: A => a.calA
  case b: B => b.calB
  case i: Int => i + 5
  case s: String => s.toUpperCase
}
// -> List(6, "S", "T")

list groupBy {
  case a: E => "E" // grouping A, B and C together
  case i: Int => "Int"
  case s: String => "String"
}
// -> Map("Int" -> List(1), "String" -> List("s", "t"))
相关问题