Scala Syntax: 7 Points
Scala Syntax: 7 Points
Join the DZone community and get the full member experience.Join For Free
Get the Edge with a Professional Java IDE. 30-day free trial.
back I dipped into some Scala as a hobby language. Recently, in order to get a quick overview of Spark I did 'Big Data Analysis with Scala and Spark' fromCoursera
It's a great course. But, one aspect I found challenging was just getting my head around Scala syntax again. Some of it, yeah thebasic stuff
can be counter intuitive depending on your perspective.
1. Method/Function DefinitionTyping on the right rather than the left. Consider this simple function definition:
Javaholics will note:
- The return is specified at the end of the method definition, rather than the beginning.
- The type of the parameter is specified after the parameter name rather than before.
- Before the function body there is a =
- There are two colons (:), one between the parameter and the type and one before the return type.
Google "Unit" and you be quickly told you that Unit is the Scala's version of Java void. But, Java’s void is akeyword
. Scala’s Unit is a final class which only has one value: () - which is like an alias for no information. Unit indicates a method returns nothing and therefore has side effects, something we don't want to do much of in Scala. So is that counter intuitive? No.
But here is what I find is. If a function has no return type in the function definition and no equals it means Unit is implicitly the return type. Example:
Big deal? Of course not. But what about:
Expect the String to be returned, it wont be. How about this?
This will give a compile warning::12: warning: enclosing method addNumbers has result type Unit: return value discarded return a + b It will compile but nothing will be returned:
will give no compile warning and will also return nothing.
In anonymous Scala functions, _ is like Groovy'sit
. In Groovy we can to multiple all numbers between 1 and 5 we can do:
In Scala we can do:
However, in Scala, the second time _ is referenced, it refers to the second parameter
4. Passing Anonymous Functions
Pass one anonymous function and you don't need any curly parenthesis. Pass two and you do.
When a method has no arguments, (arity-0), the parentheses can be omitted in invocation
But this technique should never be used when method has side effects. So,
6. Declare parameter types
Function defiinitions / Method definition have to declare parameter types but function literals don’t.
7. Ternary Operator
Published at DZone with permission of Alex Staveley , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.