Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to print sum of 2 numbers in scala?

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
  }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading