小编ped*_*nto的帖子

泛型的Scala模式匹配

我有一个“字符串”列表(类String的包装,名为Str),其中一些具有混合特征。在某个时间点上,我需要区分mixin特性以提供其他功能。

我的代码可以恢复为此,并且可以正常工作:

case class Str(s: String)
trait A
trait B

object GenericsPatternMatch extends {
  def main(args: Array[String]): Unit = {

    val listOfStr: Seq[Str] =
      Seq(
        Str("String"),
        new Str("String A") with A, // Some trait mixins
        new Str("String B") with B
      )

    println("A: " + selectStrA(listOfStr))
    println("B: " + selectStrB(listOfStr))
  }

  val selectStrA: Seq[Str] => Seq[Str with A] = (strList: Seq[Str]) => strList.collect { case s: A => s }
  val selectStrB: Seq[Str] => Seq[Str with B] = (strList: Seq[Str]) => …
Run Code Online (Sandbox Code Playgroud)

generics scala pattern-matching

5
推荐指数
1
解决办法
114
查看次数

标签 统计

generics ×1

pattern-matching ×1

scala ×1