I am completely new to Scala. I like to add 2 numbers in scala. However I am not getting any output. Can anyone please help?
I am getting the output as "Sum is ()"
The below code should give the output as "Sum is 15".
object test1 {
def main(args: Array[String]):Unit={
val obj= new A();
println("Sum is " + obj.curr())
}
}
class A{
private var value=6
def curr()={
var result= value +9
}
}
>Solution :
In Scala, the return of a method is the last expression.
In your case curr() returns Unit (no value).
To make it return a value, change it to:
def curr(): Int = {
var result= value +9
result
}
Note that you can actually just write it as the following:
def curr(): Int = value + 9
Also note that I’ve added the return type of the mode explicitly, this is a good practice as it will raise a compilation error if you don’t return the type that you said you would return.
More generally, if you’re new to Scala, take the time to learn the basics and the idiomatic way to write Scala.
For instance, vars are to be avoided unless strictly necessary and locally scoped.