0

I was learning about scala methods and I created two code examples which are somewhat similar in nature, but confused on calling them.

Method #1

def someTestMethod = {
    println("Inside a test method")
}

This resorts to a Unit type since it does not return anything.

Method #2

def anotherTestMethod() = {
    println("Inside a test method")
}

This resorts to Unit as well, but with a curly brace () added.

What is the difference between the two methods, notice that if I call the first method like someTestMethod(), the scala shell/compiler says

error: Unit does not take parameters, but works well if I call like someTestMethod without the braces.

Also, the second method seems fool proof, in the sense that it can be called either way anotherTestMethod or anotherTestMethod(), why is it so?

Greedy Coder
  • 1,256
  • 1
  • 15
  • 36

1 Answers1

-2

When you don't want to pass any parameter to the method, use the first one.

If you want to pass some pass parameters, use the second one with brackets and pass some parameters and use it inside method.

For example:

def someTestMethod1(count : Int) = {
    println("Inside a test method"+count)
  }

  someTestMethod1(10)
Shankar
  • 8,529
  • 26
  • 90
  • 159
  • This is almost entirely wrong. Of course you need () to pass parameters, but there is a difference with no parameters and you don't want to always use it without (as the linked-to duplicate explains). – The Archetypal Paul Sep 19 '16 at 12:18