functionscalamethodsscalastyle

Scala "def" method declaration: Colon vs equals


I am at the early stages of learning Scala and I've noticed different ways to declare methods.

I've established that not using an equals sign makes the method a void method (returning a Unit instead of a value), and using an equals sign returns the actual value so

def product(x: Int, y: Int) {
  x*y
}

will return () (Unit), but

def product(x: Int, y: Int) = {
  x*y
}

will return the product of the two arguments(x*y)

I've noticed a third way of declaring methods - with a colon. Here is an example

def isEqual(x: Any): Boolean

How does this differ from the = notation? And in what situations will it be best to use this way instead?


Solution

  • When you use colon (and use equal) you explicitly define return type of method.

    // method return Boolean value
    def m(a : Int) : Boolean = a > 0 
    

    When you don't use colon and use equal you allow scala compiler inferring return type itself.

    // method has return type of last expression (Boolean)
    def m(a : Int) = a > 0 
    

    When you use neither colon nor equal your method has return type of Unit class.

    // method has Unit return type
    def m(a : Int){ 
        a > 0 
    }