Search code examples
scalapattern-matchingunreachable-codenon-exhaustive-patterns

Unreachable case except for null in scala


I have the following helper function. I am trying to create a word frequency List. (a,b,a) => [(a,2),(b,1)]:

def add_to_lop(c:Char, lop: List[(Char, Int)]):List[(Char, Int)] = {
      lop match {
        case List() => List((c,1))
        case (c, _)::xs => add_to_pair(c,lop.head)::lop.tail
        case _ => lop.head::add_to_lop(c, lop.tail)
      }

I think so long as the head of lop does not satisfy lop.head._1==c, the case should reach the third one (barring lop being empty where it is the first case). However compilation warns that the third case is almost unreachabe - case _ => lop.head::add_to_lop(c, lop.tail); Unreachable case except for null (if this is intentional, consider writing case null => instead).. Can you help me identify my mistake?


Solution

  • Write

    case (`c`, _)::xs =>
    

    with backticks instead of

    case (c, _)::xs =>
    

    In the pattern, c without backtics is a new variable, so matches everything, not only the previous c.

    scala Does match end in Nil?