Scala function returns Unit but should return Int

I just started learning Scala last week. I created a stub method in one of my programs but was getting an error. Here’s my function:

def howMuch(max: Int) {
  var n = 0

I tried to use the result in expression, e.g.

var m = 1
var n = howMuch(100)
m += n

Here’s the error I received:

error: overloaded method value - with alternatives:
  (x: Int)Int <and>
  (x: Char)Int <and>
  (x: Short)Int <and>
  (x: Byte)Int
 cannot be applied to (Unit)
             m += n

It seemed clear to me that my function should be returning an Int, namely zero. Why was it returning the Unit value?

Answer: a missing equals sign in the function assignment. Here’s the function that returns an Int:

def howMuch(max: Int) = {
  var n = 0

One thought on “Scala function returns Unit but should return Int”

  1. This mistake is made almost by everyone beginning with Scala. Therefore, many people favor abandoning the “procedure syntax” (`def foo() {}` `def foo() = ()`). It will likely be required to use the equals sign in a future Scala version.

Leave a Reply

Your email address will not be published. Required fields are marked *