3

In my Scala code below, use foreach to loop through a Tuple List,

val t1 = List((1,"A"), (2, "B"))

t1.foreach{
  case(id, name) => println(id, name)
}

t1.foreach(x => println(x))

t1.foreach(case(id, name) => println(id, name))

error: illegal start of simple expression
           t1.foreach(case(id, name) => println(id, name))
                      ^

Why {} works, first () works, but last () return an error ?

Charlie 木匠
  • 2,234
  • 19
  • 19
  • 3
    See https://stackoverflow.com/questions/4386127/what-is-the-formal-difference-in-scala-between-braces-and-parentheses-and-when - specifically, check out "Function/Partial Function literals with case" section in the accepted answer. – Tzach Zohar Jul 03 '18 at 20:17
  • scala> ` t1.foreach( x => | x match (case(id, name) => println(id, name))` :2: error: '{' expected but '(' found. x match (case(id, name) => println(id, name)) – Charlie 木匠 Jul 04 '18 at 17:44
  • This works: ''' t1.foreach( x => x match {case(id, name) => println(id, name)} ) ''' – Charlie 木匠 Jul 04 '18 at 17:44
  • Seems `match` needs to be followed with {} – Charlie 木匠 Jul 04 '18 at 17:45

0 Answers0