Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use " " ( space ) and when to use . ( dot ) when invoking methods in Scala?

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?

like image 910
OscarRyz Avatar asked Aug 03 '10 18:08

OscarRyz


People also ask

What does => mean in scala?

=> 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 .

What is the syntax of defining method in scala?

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.

How do you run a method in scala?

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.

How do you call a method in scala class?

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.


2 Answers

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.)

like image 167
mipadi Avatar answered Oct 12 '22 00:10

mipadi


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.

like image 40
huynhjl Avatar answered Oct 12 '22 00:10

huynhjl