Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a function does not return or return void in scala

Tags:

scala

With more and more confused raised up, I even find that I can not understand simple Function definition in Scala:

If I just want to define a function doing nothing but some unuseful addition, how can I do that like this:

def nothing(a:Int, b:Int) = {
    a = a+1; b=b+1;
}

What I want is add 1 to a and b and return nothing or void.

I kinda feel the more I learnt, the more I begin unfamiliar with, even to those I learnt before, this is terrible.

like image 887
Kuan Avatar asked Nov 29 '22 10:11

Kuan


2 Answers

Your question boils down to two parts:

1) How do I define function which returns nothing? Pretty easy, just encode it to type signature, Unit is the scala way to say void (they're the same actually, java function that returns void will return Unit in scala world):

scala> def foo(x: Int): Unit = x * x
foo: (x: Int)Unit

scala> foo(1)

scala> 

Previously scala encouraged so called procedure definition (see, no equals sign):

scala> def foo(x: Int) { x * x }
foo: (x: Int)Unit

scala> foo(2)

scala> 

But it's error prone and thus discouraged.

2) How do I alter primitive that was passed into the function? You can't, scala, as well as Java does not allow this and it's for a great good.

like image 166
om-nom-nom Avatar answered Dec 05 '22 13:12

om-nom-nom


As Chris and om-nom said, you cannot alter primitive passed as arguments to a function, and will need to declare new vals. Also, you can specify the return type of your variable by appending : Unit (or any valid type) after the parameters, in the signature, as following:

 def nothing(a:Int, b:Int): Unit = { val new_a = a+1; val new_b = b+1 }

Note that the implicit type of your function was already Unit, i.e void in scala.

like image 38
Bacon Avatar answered Dec 05 '22 13:12

Bacon