小编kam*_*mov的帖子

Scala 如何使用模式匹配与非通用 LazyList?

在 Scala 2.13 中,我遇到了使用 operator 进行模式匹配的问题,使用时#::会显示错误Cannot resolve method #::.unapply,如下所示:

def exampleFunction(lazyList: LazyList[Int]):Unit =
  lazyList match {
    case LazyList() => println("End")
    case head #:: tail => println(head); exampleFunction(tail) // Cannot resolve method #::.unapply
  }
exampleFunction(LazyList(1,2,3,4,5,6,7,8))
Run Code Online (Sandbox Code Playgroud)

当 LazyList 是泛型时,运算符会按预期工作:

def exampleFunction[A](lazyList: LazyList[A]):Unit =
  lazyList match {
    case LazyList() => println("End")
    case head #:: tail => println(head); exampleFunction(tail)
  }
exampleFunction(LazyList(1,2,3,4,5,6,7,8)) // output: 1 2 3 4 5 6 7 8 End
Run Code Online (Sandbox Code Playgroud)

为什么会出现这个问题,有没有办法解决?

functional-programming scala list pattern-matching lazy-evaluation

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