
- Scala Tutorial
- Scala - Home
- Scala - Overview
- Scala - Environment Setup
- Scala - Basic Syntax
- Scala - Data Types
- Scala - Variables
- Scala - Classes & Objects
- Scala - Access Modifiers
- Scala - Operators
- Scala - IF ELSE
- Scala - Loop Statements
- Scala - Functions
- Scala - Closures
- Scala - Strings
- Scala - Arrays
- Scala - Collections
- Scala - Traits
- Scala - Pattern Matching
- Scala - Regular Expressions
- Scala - Exception Handling
- Scala - Extractors
- Scala - Files I/O
- Scala Useful Resources
- Scala - Quick Guide
- Scala - Useful Resources
- Scala - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Scala - Anonymous Functions
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 )