One thing Scala: Five — apply method

Learn
2 min readJun 15, 2021

Scala has Java as it’s base which was designed as an object oriented language. So you cannot define a method by itself, you need to have the class and the method.

Given that you have the class and the method, what you can do then is to come up with some syntactic sugar so that you can call the method within the class directly with one word which would be the “function name”. That is instead of calling “new MyClass().myMethod”, the user should be able to call “myMethod()”. Why? So that the developer feels that he is doing functional programming. He can express his solution using functional programming paradigms which is essentially syntactic sugar to hide the underlying object oriented manifestations of the functional programming code.

Nothing wrong about it. After all, object oriented programming itself is ultimately an abstraction over the underlying machine code. Scala’s functional programming just adds one more layer of abstraction over the object oriented code.

So, the syntactic “trick” with Scala is the method name “apply”. If a class has a method named apply and you create an instance of that class, then if you call the instance name as if it were a function, then the call would get redirected by Scala to the apply method.

class Doubler {
def apply(n : Int) : Int = n * 2
}

Client code would be as below

val doubler = new Doubler()
println(doubler(100))

apply method is special and has the ability to be invoked in this manner. And the above code would print 200.

--

--