Turn method into a Function in Scala

Deepak Kumar
1 min readOct 7, 2020

In Scala you have both methods and functions. A function is kind of a value which can be passed around. At times you might need to pass a something which is defined as a method but you can’t pass a method just like functions.

Scala provides an easy way to do so. Let’s take an example of sum of two numbers.

def sum(a: Int, b: Int): Int = a + b

To make that as a function you can do as follows

val sumFn = sum _

This will provide you with a value that can be passed around and you can execute it as a normal function.

The above method works differently for a variable argument method for example lets take a combine method definition as follows.

def combine(args: String*): String = args.mkString(“|”)val combineFn = combine _

Here you will get a function of the signature as below

Seq[String] => String

This is not a hack as such, it turns a method into a function that delegates to the method. But along the way it performs a lot of simplifications, including turning vararg parameters into Seq parameters.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Deepak Kumar
Deepak Kumar

Responses (2)

Write a response