scala – 为什么我不能匹配流?

特别:

scala> def f(n: Seq[Any]) = n match { 
     case Nil => "Empty" 
     case h :: t => "Non-empty" 
}
f: (n: Seq[Any])String

scala> f(Stream())
res1: String = Empty

scala> f(List(1))
res17: String = Non-empty

scala> f(Stream(1))
scala.MatchError: Stream(1, ?) (of class scala.collection.immutable.Stream$Cons)
  at .f(<console>:13)
  ... 33 elided

还有很多其他方法可以实现这一点,但在编写代码时,代码是静态安全的,并且在运行时失败.这是怎么回事?

最佳答案 对于Stream,concat符号应为#::,模式匹配应如下:

  def f(n: Seq[Any]) = n match {
    case Nil => "Empty"
    case h :: t => "Non-empty"
    case h #:: t => "Non-empty stream"
  }

for :: is for List / Seq type(List from Seq :)),参见:

final case class ::[B](override val head: B, private[scala] var tl: List[B]) extends List[B] {
点赞