Thursday, September 24, 2009

Case-sensitive matching

One possibly surprising rule of matching is that lowercase identifiers in the case clause always have a value bound to them but if the identifier starts with an uppercase character the identifier is used as a value to match against.

  1. scala> val iWantToMatch = 10
  2. iWantToMatch: Int = 10
  3. scala> val iDontWantToMatch = 1
  4. iDontWantToMatch: Int = 1
  5. scala> 10 match {
  6.      | case iDontWantToMatch => "boo"
  7.      | case iWantToMatch => "yay"
  8.      | }
  9. :7: error: unreachable code
  10.        case iWantToMatch => "yay"
  11.                             ^
  12. // we have an error because iDontWantToMatch is treated as a parameter to the iDontWantToMatch => "boo" function.
  13. // Not as a value to match against.
  14. // in this example you can see how iDontWantToMatch is has 10 bound to it
  15. scala> 10 match {
  16.      | case iDontWantToMatch => iDontWantToMatch
  17.      | }
  18. res9: Int = 10
  19. // back tick forces the value to be matched against
  20. scala> 10 match {
  21.      | case `iDontWantToMatch` => "boo"
  22.      | case `iWantToMatch` => "yay"
  23.      | }
  24. res7: java.lang.String = yay
  25. scala> val IWantToMatch = 10
  26. IWantToMatch: Int = 10
  27. scala> val IDontWantToMatch = 1
  28. IDontWantToMatch: Int = 1
  29. // also if first character is upper case it is matched against.
  30. scala> 10 match {
  31.      | case IDontWantToMatch => "boo"
  32.      | case IWantToMatch => "yay"
  33.      | }
  34. res8: java.lang.String = yay

1 comment:

  1. Simple,

    with first upper letter it is a constant. With an lower letter it is a variable Name and have to be in back ticks.

    ReplyDelete