Scala - Anonymous Functions


Advertisements

Scala provides a relatively lightweight syntax for defining anonymous functions. Anonymous functions in source code are called function literals and at run time, function literals are instantiated into objects called function values.

Scala supports first-class functions, which means functions can be expressed in function literal syntax, i.e., (x: Int) => x + 1, and that functions can be represented by objects, which are called function values.

Try the following expression, it creates a successor function for integers −

var inc = (x:Int) => x+1

Variable inc is now a function that can be used the usual way −

var x = inc(7)-1

It is also possible to define functions with multiple parameters as follows −

var mul = (x: Int, y: Int) => x*y

Variable mul is now a function that can be used the usual way −

println(mul(3, 4))

It is also possible to define functions with no parameter as follows −

var userDir = () => { System.getProperty("user.dir") }

Variable userDir is now a function that can be used the usual way −

println( userDir )
scala_functions.htm

Useful Video Courses


Video

Scala Online Training

82 Lectures 7 hours

Arnab Chakraborty

Video

Apache Spark with Scala - Hands On with Big Data

23 Lectures 1.5 hours

Mukund Kumar Mishra

Video

Delta Lake with Apache Spark using Scala

52 Lectures 1.5 hours

Bigdata Engineer

Video

Apache Spark with Scala useful for Databricks Certification

76 Lectures 5.5 hours

Bigdata Engineer

Video

Machine Learning with Apache Spark 3.0 using Scala

69 Lectures 7.5 hours

Bigdata Engineer

Advertisements