0

I'm new to Scala programming and have a question on an error. I have defined a method inside a class. Below is the code (Private_Rational is the class name)

 def + (that: Private_Rational): Private_Rational = { new Private_Rational(numer * that.denom + that.numer * denom, denom * that.denom) println("I'm in first plus") } 

The above code flashed an error (it forced me to use Unit as the return type), however when I moved the println statement above the new statement, it worked

 def + (that: Private_Rational): Private_Rational = { println("I'm in first plus") //Moved println here new Private_Rational(numer * that.denom + that.numer * denom, denom * that.denom) } 

Can anyone please enlighten on why the compiler didn't like the first one? Appreciate your help. -Thanks.

3
  • 2
    Why would it work in the first case? Commented Aug 24, 2022 at 15:01
  • 3
    After some research found that Scala functions must return something and it returns the last executed statement. Println is not a returnable statement while the new statement does some computations and returns a value. I think that's the reason. Commented Aug 24, 2022 at 15:03
  • There's no "returnable statement". println returns Unit that's all. Commented Aug 24, 2022 at 17:30

2 Answers 2

2

When you wrote the println() call at the end, you are executing that function and returning the result of that function. If you check the code of println() (hover over the function on Intellij and press CTRL while clicking on the function) you can see this:

 def println(): Unit = Console.println() 

As you can see, the return type of that function is Unit. That's why the compiler was complaining about. Your function + was supposed to return a Private_Rational but you were returning Unit instead

Sign up to request clarification or add additional context in comments.

Comments

1

The last expression you write in your method will define the return type of the method. Think of it as the method was written as

 def + (that: Private_Rational): Private_Rational = { new Private_Rational(numer * that.denom + that.numer * denom, denom * that.denom) return println("I'm in first plus") } 

As Jaime pointed out, the println() method return type is Unit; that's why the compiler is warning about the return type.

If you switch the statements like you did, you get the expected return type, as the new Private_Rational(numer * that.denom + that.numer * denom, denom * that.denom) is now the last statement of that code block.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.