0
votes

I am a newbie in scala and started out writing some code in Eclipse. I have three methods out of which second one complains with error mentioned in subject

  def add(b:Byte):Unit = sum+=b
  def add1(b:Byte):Int = sum+=b
  def add2(b:Byte):Int = sum

Why is the third method not complaining and while second method does ? The code I wanted to write was something like "add b to sum an return the new sum" as concisely as possible. So even after declaring a return type of Int in second method, why doesn't scala understand an implicit return in the second method while it does the same for third method ?

1
If you want to return sum: def add1(b:Byte):Int ={ sum+=b; sum }insan-e
@insaan-e - Thanks for that, I understood the point!!userx

1 Answers

2
votes

The return type of += is Unit. So add1 implicitly returns what += returns and that's Unit.