kamov
kamov

Reputation: 113

Scala How to use pattern matching with a non generic LazyList?

In Scala 2.13 I have encountered a problem with pattern matching using the operator #::, which displays error Cannot resolve method #::.unapply when used as follows:

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))

When the LazyList is generic, the operator does work as expected:

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

Why does this problem occur and is there a way to fix it?

Upvotes: 5

Views: 1029

Answers (1)

Mario Galic
Mario Galic

Reputation: 48420

In case you are using IntelliJ, this might be due to in-editor error highlighting bug SCL-15834: Highlighting error on case matching using operator #:: In other words, this is a false positive where the code compiles successfully however IntelliJ's custom error highlighting process incorrectly identifies a problem. Providing explicit import

import scala.collection.immutable.LazyList.#::

seems to make the editor error highlighting happy, however the import should not be necessary. Few other suggestion to try

  • File | Invlidate Caches
  • From the root of the project rm -fr .idea and then re-import project
  • Update to bleeding edge Scala Plugin version: Preferences | Languages & Frameworks | Scala | Updates | Update channel | Nightly Builds
  • Within Registry... enable experimental flag scala.highlighting.compiler.errors.in.editor

Upvotes: 3

Related Questions