3

I have the following code:

object testLines extends App {
    val items = Array("""a-b-c  d-e-f""","""a-b-c   th-i-t""")
    val lines = items.map(_.replaceAll("-", "")split("\t"))
    print(lines.map(_.mkString(",")).mkString("\n"))
}

By mistake i did not put a dot between replaceAll and split but it worked.

By contrary when putting a dot between replaceAll and split i got an error

  • identifier expected but ';' found.
  • Implicit conversions found: items =>

What is going on? Why does it work without a dot but is not working with a dot.

Update: It works also with dot. The error message is a bug in the scala ide. The first part of the question is still valid

Thanks,

David

David Michael Gang
  • 7,107
  • 8
  • 53
  • 98
  • It works fine for me in REPL with or without the dot between `replaceAll` and `split`... – Patryk Ćwiek Nov 20 '13 at 14:06
  • Why does it work without dots?The second part is interesting. It gives me an error in the scala ide, so it is maybe a bug in the scala ide – David Michael Gang Nov 20 '13 at 14:09
  • seems strange that it would tell you that it found an unexpected semicolon when there is none – stew Nov 20 '13 at 14:13
  • yes. it is a sort of bug. because when i close the file and open it again the error is gone. But why does it work without dot? – David Michael Gang Nov 20 '13 at 14:17
  • 1
    because dots can (sometimes) be omitted: http://stackoverflow.com/questions/1181533/what-are-the-precise-rules-for-when-you-can-omit-parenthesis-dots-braces-f – Leo Nov 20 '13 at 14:32

1 Answers1

2

You have just discovered that Operators are methods. x.split(y) can also be written x split y in cases where the method is operator-like and it looks nicer. However there is nothing stopping you putting either side in parentheses like x split (y), (x) split y, or even (x) split (y) which may be necessary (and is a good idea for readability even if not strictly necessary) if you are passing in a more complex expression than a simple variable or constant and need parentheses to override the precedence.

With the example code you've written, it's not a bad idea to do the whole thing in operator style for clarity, using parentheses only where the syntax requires and/or they make groupings more obvious. I'd probably have written it more like this:

object testLines extends App {
    val items = Array("a-b-c  d-e-f", "a-b-c   th-i-t")
    val lines = items map (_ replaceAll ("-", "") split "\t")
    print(lines map (_ mkString ",") mkString "\n")
}
pndc
  • 3,710
  • 2
  • 23
  • 34