1

I'm working my way through the Coursera course on functional programming in Scala and have encountered behavior that appears to differ from the language's description. According to the lecture on pattern matching, the output of the second println statement should be false rather than true in the following Scala spreadsheet:

object MatchTest {
  def test(char: Char, list: List[Char]): Boolean = list match {
    case char :: tail => true
    case _            => false
  }                                               //> test: (char: Char, list: List[Char])Boolean

  println(test('a', "ab".toList))                 //> true
  println(test('b', "ab".toList))                 //> true
}

Why does the second test match on char :: tail and not match on _?

Steve Emmerson
  • 7,702
  • 5
  • 33
  • 59

1 Answers1

2

The char variable in case char :: tail => true is not referring to the test() method parameter, but is actually shadowing it.

You need to use:

def test(char: Char, list: List[Char]): Boolean = list match {
    case `char` :: tail => true
    case _              => false
}   

If you use backticks, you are matching against the value of char. Without it, you are creating a new variable that will match any character.

Interestingly, you could also use a variable name with first uppercase letter. The convention is that lower case names refer to match variables, whereas upper case names refer to identifiers from the outer scope:

def test(MyChar: Char, list: List[Char]): Boolean = list match {
    case MyChar :: tail => true
    case _            => false
}    

As mentioned here, it has to do with stable identifiers.

Community
  • 1
  • 1
Mifeet
  • 12,949
  • 5
  • 60
  • 108