I've seen Scala using both interchangeably, but I don't know when to use one or the other.
Is there a convention?
For instance these are equivalent
"hello" toString
and
"hello".toString()
And they can even be mixed
"hello".toString() length
What's the convention?
=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .
Syntax. def functionName ([list of parameters]) : [return type] = { function body return [expr] } Here, return type could be any valid Scala data type and list of parameters will be a list of variables separated by comma and list of parameters and return type are optional.
You should see a tiny green arrow either on the left hand side of your main class or when right clicking within that class. Also, if you are on macOS there is the ctrl+shift+r to run the file as shown in the image below.
In the basic use case, the syntax to invoke a method in an immediate parent class is the same as Java: Use super to refer to the parent class, and then provide the method name.
The space convention is generally used when the method functions like an operator (+
, *
, etc.); the dot convention is used when it functions more like, well, a method call.
(I know that explanation is kind of vague, but there's not really a hard and fast rule for the usage.)
To expand on the comment from Yardena, there is an Scala unofficial style guide. It has some suggestions on when to use the dot notation and when to drop the dot and the parenthesis and usually provides a brief rationale for the recommendation, that you may or may not agree with, but at least that's a starting point.
For instance name toList
may behave differently depending on what's on the next line.
Personally, I would write hello.toString.length
with the assumption that all calls are side-effect free (so I drop the parenthesis) and then I have to keep the dot for it to compile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With