Home > Software engineering >  Scala method in a class forcing to use Unit (using IntelliJ editor)
Scala method in a class forcing to use Unit (using IntelliJ editor)

Time:08-26

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.

CodePudding user response:

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

CodePudding user response:

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.

  • Related