Search code examples
scalasyntaxidentifierlexical-analysis

Why Scala By-Name parameter syntax fails when removing space between : and =>


I am just having a question in my mind regarding the named parameters syntax of Scala. I have created the below running code fragment and it works fine. However, when I removed the Space between a: =>Int to a:=>Int, it fails.

This runs without any issues:

object Calculator extends App {
  def sum(a: => Int) = (b: Int) => a + b
  println(sum(4)(5))
}

The following fails with a syntax error when I remove space at Line 2 in sum(a:=>Int):

object Calculator extends App {
  def sum(a:=> Int) = (b: Int) => a + b
  println(sum(4)(5))
}

Why doesn't the second code snippet compile?


Solution

  • It fails at the very first stage, during the lexical analysis, because :=> is a valid Scala identifier:

    val :=> = 42
    println(:=>)  // prints 42
    

    Therefore, your code

    def sum(a:=> Int) = ??? // wrong: unexpected identifier `:=>`
    

    is just as invalid as, say

    def sum(a+= Int) = ??? // wrong: unexpected identifier `+=`
    

    or

    def sum(a:: Int) = ??? // wrong: unexpected identifier `::`