Functions in Scala

As scala is functional programming we will be able to use functions as first class citizens (passing functions as arguments, returning functions as return type, assigning functions to variables…)
But the problem is that scala sits on top of JVM and JVM is designed for Object Oriented Programming. Scala solves this problem like this

trait MyFunction[A, B] {
  def apply(element: A): B
}
// Java way of implementing above function aka Anonymous Function
val doubler = new MyFunction[Int, Int] {
  // does not need 'override keyword for trait methods'
  def apply(e: Int): Int = e * 2
}
println(doubler(5)) // prints 10

For this reason, to enable developers make use of functional programming concepts, scala provided pre-defined traits/functions (Function1 till Function22) that can take up to 22 generic parameters.
Function1 takes 1 type as input (input param) and return 1 type as output (return type). For example, we can redefine above implementation like this

val scalaDoubler = new Function1[Int, Int] {
  def apply(a: Int) = a * 2
}
println("Scala Doubler: "+scalaDoubler(5))

Apply Method: This method is very special and allows us to call instances of classes or singleton objects like they were functions. And functions are actually instances of classes with apply method.
Anonymous Functions
In scala we can write anonymous function as LAMBDA.
Same Function1 above can be re-written as below different ways

val scalaDoubler1 = (a: Int) => a * 2
or
val scalaDoubler1: (Int => Int) = a => a * 2
or
val scalaDoubler1: (Int => Int) = _ * 2
println(scalaDoubler1(5))
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Mawazo

Mostly technology with occasional sprinkling of other random thoughts

amintabar

Amir Amintabar's personal page

101 Books

Reading my way through Time Magazine's 100 Greatest Novels since 1923 (plus Ulysses)

Seek, Plunnge and more...

My words, my world...

ARRM Foundation

Do not wait for leaders; do it alone, person to person - Mother Teresa

Executive Management

An unexamined life is not worth living – Socrates

javaproffesionals

A topnotch WordPress.com site

thehandwritinganalyst

Just another WordPress.com site

coding algorithms

"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." -- John Tukey

%d bloggers like this: