how to convert this java code to scala ? Scala doesn't prefer 'return', then scala has a better version ?
public void myMethod(String name){
if(s==null) return;
//other logic and many lines ....
}
how to convert this java code to scala ? Scala doesn't prefer 'return', then scala has a better version ?
public void myMethod(String name){
if(s==null) return;
//other logic and many lines ....
}
Let's do this in two steps:
def myMethod(name: String): Unit =
if(name == null) () else{
//rest of code that works via side-effect
}
The ()
denotes an instance of Unit
.
That's ok but there's something even better! This take advantage that the Option
constructor has special null
handling, e.g. Option(null) == None
.
def myMethod(name: Option[String]): Unit = name.foreach{
//rest of code that works via side-effect
}
Wherein if you might have something which could be null
you will make sure that the type system specifies that the variable might or might not contain a value (yes, Java now has Optional
too and for similar reasons!)
Or refactor the code in this way:
def myMethod(name: String) = {
if (name != null) {
//other logic and many lines ....
}
}
The short answer is that you don't need to use the return keyword. The return is Scala is pretty much explained here pretty much but I'd like to point out a few things.
Most constructs in Java are statements which means they only executed, not evaluated. This is quite important because in Scala most of these constructs are expressions. Let's see how this works on an if-construct.
// Initialize i to 1 if some condition is true otherwise to 0
int i;
if (someCondition) i = 1;
else i = 0;
Assuming we'd like to initialize i in one step (maybe we'd like making it final) we need to use a ternary operator:
final int i = someCondition ? 1 : 0;
This works because the right hand side is actually an expression. Now let's write this in Scala:
val i = if (someCondition) 1 else 0
This is a conditional expression.
A good thing to keep in mind about functions is that the return value of a function is equal to the result of its last expression. This being you can define the if-expression as the latest in your function and thus its result will be returned. Applying this to your code leaves us with:
def myMethod(name: String): Int = {
if (s == null) -1
else { ... }
}
I've updated your method to return an Int
in this case for the sake of argument. You probably need to replace it with something more meaningful. On the else branch you'd also need to return an Int
in this case. Anyway I hope this clears your request.
As a closing note this is a nice guide explaining why you should avoid using return
. Personally I haven't used it at all even though there are some examples there.