Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala procedure and function differences

Tags:

scala

I am learning Scala and running below code .I knew functions, that do not return anything is procedures in Scala but when running below code why extra () is coming in output. Here in procedure i am just printing the value of 'value'. Can someone explain about this.

class Sample{
  private var value = 1
  def test()  {value += 2; println(value)} 
  def test2() = value
}

object Main2 extends App {
  val my_counter = new Sample()
  println(my_counter.test())
  println(my_counter.test2())

}

3
()
3
like image 708
anwaar_hell Avatar asked Jan 25 '26 16:01

anwaar_hell


1 Answers

The so-called "procedure syntax" is just "syntactic sugar" for a method that returns Unit (what you would call void in Java).

def sayHello(toWhom: String) {
  println(s"hello $toWhom")
}

Is semantically equivalent (and gets actually translated) to:

def sayHello(toWhom: String): Unit = {
  println(s"hello $toWhom")
}

Notice the explicit type and the equal sign right after the method signature.

The type Unit has a single value which is written () (and read unit, just like it's type). That's what you see: the method test prints value and then produces () of type Unit, which you then move on to print on the screen itself.

As noted in a comment, the "procedure syntax" is deprecated and will be removed in Scala 3.

like image 135
stefanobaghino Avatar answered Jan 27 '26 09:01

stefanobaghino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!