The following is snippet of an example from page 240 of the book Programming Scala (Wampler & Payne, 2009; O'Reilly Media):

/** @return Parser[Money] */
def deductItem = deductKind ~> deductAmount

Is there any reason to do this instead of just specifying the return type with an actual type annotation, as below?

def deductItem: Parser[Money] = deductKind ~> deductAmount
  • 7
    I would point out that Scala has changed fairly significantly from 2009 to 2015. This is quite a bit like comparing advice given in a first edition K&R to C11.
    – user40980
    Dec 17, 2015 at 22:10

1 Answer 1


Sometimes in Scala, you break from the normal syntax to make something that looks like a DSL. Parser combinators are one of those areas. Putting the type annotation would break the DSL illusion of looking grammar-like. Some development teams care about that more than others. Some development teams care about the type annotation more.

I would prefer to omit the comment too. However, when explaining it to others, such as in a textbook, it's occasionally useful to show the type.

Note that this is definitely a special case. Your type checker works best for you when you put explicit return type annotations for all your functions, and that's the recommended practice in most cases. Of course, if you're like me and tend to forget exactly how parser combinators work when you don't use them for a while, you can "cheat" by putting in the types at first, then remove them later to make it look pretty.

  • Oh yeah, that does make a lot of sense. I've seen and used DSLs before (most notably Gradle and ScalaTest), but it didn't occur to me that aesthetics was the first optimization consideration here. Dec 18, 2015 at 1:35
  • Or, rather, it didn't occur to me that the authors might have intended the type annotation to "actually" be left out completely, but put one in - one that doesn't disturb the line that would be left in - for clarity. Dec 18, 2015 at 10:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.