Scala in a nutshell
2
Agenda
 Why Scala ?
 Difference b/w Java and Scala
 Scala Data Types
 Scala Variables
 Scala Classes & Objects
 Scala Functions
 Scala Closures
 Scala Exception Handling
 Scala Collections
3
Java
What’s wrong with Java?
Not designed for highly concurrent programs
• The original Thread model was just wrong (it’s been fixed)
• Java 5+ helps by including java.util.concurrent
Verbose
• Too much of Thing thing = new Thing();
• Too much “boilerplate,” for example, getters and setters
What’s right with Java?
Very popular
Object oriented (mostly), which is important for large projects
Strong typing (more on this later)
The fine large library of classes
The JVM! Platform independent, highly optimized
4
Scala is like Java, except when it isn’t
Java is a good language, and Scala is a lot like it
For each difference, there is a reason--none of the changes
are “just to be different”
Scala and Java are (almost) completely interoperable
Call Java from Scala? No problem!
Call Scala from Java? Some restrictions, but mostly OK.
Scala compiles to .class files (a lot of them!), and can be run with
either the scala command or the java command
To understand Scala, it helps to understand the reasons for
the changes, and what it is Scala is trying to accomplish
5
Verbosity
Java:
class Person {
private String firstName;
private String lastName;
private int age;
public Person(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public void setFirstName(String firstName) { this.firstName = firstName; }
public void String getFirstName() { return this.firstName; }
public void setLastName(String lastName) { this.lastName = lastName; }
public void String getLastName() { return this.lastName; }
public void setAge(int age) { this.age = age; }
public void int getAge() { return this.age; }
}
Scala:
class Person(var firstName: String, var lastName: String, var age: Int)
6
Genealogy
Scala
Java
C
C++
Simula
Smalltal
k
Prolog
Erlang
Haskell
ML
Lisp
functional
programming syntax
objects
pattern
matching
Actors
Getting Scala
Download ScalaIDE: http://scala-ide.org/
This is a customized version of Eclipse
Already using Eclipse? It’s okay to have more than one version
Scala can also be obtained by itself:
http://www.scala-lang.org/downloads
You can use the Scala documentation online,
http://www.scala-lang.org/downloads
or download it and use it locally,
http://www.scala-lang.org/downloads
Documentation is not always complete or easy to read
The source is directly available from the documentation
Hello World
/** Everybody's first program */
object HelloWorld {
def main(args: Array[String]) {
println("Hello, World!")
}
}
Save on a file named HelloWorld.scala
Compile with scalac HelloWorld.scala (or from your IDE)
Run with scala HelloWorld (or from your IDE)
Generate documentation with scaladoc HelloWorld.scala
The above code creates a singleton object
Everything in the object is like Java’s static
Scala doesn’t have static
Scala does have classes; we’ll get to those later
8
9
Scala Data Types
- Scala has all the same data types as Java, with the same memory footprint and precision.
– Byte 8 bit signed value. Range from -128 to
– Short 16 bit signed value. Range -32768 to 32767
– Int 32 bit signed value. Range -2147483648 to 2147483647
– Long 64 bit signed value. -9223372036854775808 to 9223372036854775807
– Float 32 bit
– Double 64 bit
– Char 16 bit unsigned Unicode character.
– String A sequence of Chars
– Boolean Either the literal true or the literal false
– Unit Corresponds to no value
– Null null or empty reference
– Nothing The subtype of every other type; includes no values
– Any The supertype of any type; any object is of type Any
– AnyRef The supertype of any reference type
10
Scala variables
– Variables are nothing but reserved memory locations to store values. This means
that when you create a variable, you reserve some space in memory.
– Types of Variables : Var ( mutable variable) , Val (immutable variable)
Example
object Demo {
def main(args: Array[String]) {
var myVar :Int = 10;
val myVal :String = "Hello Scala with datatype declaration.";
var myVar1 = 20;
val myVal1 = "Hello Scala new without datatype declaration.";
println(myVar); println(myVal); println(myVar1);
println(myVal1);
}
}
Output
10
Hello Scala with datatype declaration.
20
Hello Scala without datatype declaration.
11
Scala Classes & Objects
Basic Class
Example
import java.io._
class Point(val xc: Int, val yc: Int) {
var x: Int = xc
var y: Int = yc
def move(dx: Int, dy: Int) {
x = x + dx
y = y + dy
println ("Point x location : " + x)
println ("Point y location : " + y)
}
}
object Demo {
def main(args: Array[String]) {
val pt = new Point(10, 20)
pt.move(10, 10)
}
}
12
Scala Functions
- A function is a group of statements that perform a task.
- A Scala method is a part of a class which has a name, a signature, optionally some
annotations, and some bytecode
- A function in Scala is a complete object which can be assigned to a variable.
- A function definition can appear anywhere in a source file and Scala permits nested
function definitions, that is, function definitions inside other function definitions.
- Scala function's name can have characters like +, ++, ~, &,-, --, , /, :, etc.
Function Declarations
def functionName ([list of parameters]) : [return type]
Function Definitions
def functionName ([list of parameters]) : [return type] = {
function body
return [expr]
}
13
Scala Functions cont.
Example
object Demo {
def main(args: Array[String]) {
println( "Returned Value : " + addInt(5,7) );
}
def addInt( a:Int, b:Int ) : Int = {
var sum:Int = 0
sum = a + b
return sum
} }
Types of Scala Functions
Functions Call-by-Name Functions with Named Arguments
Function with Variable Arguments Recursion Functions
Default Parameter Values Higher-Order Functions
Nested Functions Anonymous Functions
14
Functions Call-by-Name
- A call-by-name mechanism passes a code block to the call and each time the call accesses
the parameter, the code block is executed and the value is calculated.
Example
object Demo {
def main(args: Array[String]) {
delayed(time());
}
def time() = {
println("Getting time in nano seconds")
System.nanoTime
}
def delayed( t: => Long ) = {
println("In delayed method")
println("Param: " + t)
}
}
Output
In delayed method
Getting time in nano seconds
Param: 2027245119786400
15
Functions with Named Arguments
- Named arguments allow you to pass arguments to a function in a different order.
Example
object Demo {
def main(args: Array[String]) {
printInt(b = 5, a = 7);
}
def printInt( a:Int, b:Int ) = {
println("Value of a : " + a );
println("Value of b : " + b );
}
}
Output
Value of a : 7
Value of b : 5
16
Functions with Variable Arguments
- Scala allows you to indicate that the last parameter to a function may be repeated. This
allows clients to pass variable length argument lists to the function.
Example
object Demo {
def main(args: Array[String]) {
printStrings("Hello", "Scala", "Python");
}
def printStrings( args:String* ) = {
var i : Int = 0;
for( arg <- args ){
println("Arg value[" + i + "] = " + arg );
i = i + 1;
}
}
}
Output
Arg value[0] = Hello
Arg value[1] = Scala
Arg value[2] = Python
17
Recursion Functions
- Recursion plays a big role in pure functional programming and Scala supports recursion functions very
well. Recursion means a function can call itself repeatedly.
Example
object Demo {
def main(args: Array[String]) {
for (i <- 1 to 4)
println( "Factorial of " + i + ": = " + factorial(i) )
}
def factorial(n: BigInt): BigInt = {
if (n <= 1)
1
else
n * factorial(n - 1)
}
}
Output
Factorial of 1: = 1
Factorial of 2: = 2
Factorial of 3: = 6
Factorial of 4: = 24
18
Default Parameter values for a Function
- Scala lets you specify default values for function parameters.
Example
object Demo {
def main(args: Array[String]) {
println( "Returned Value : " + addInt() );
}
def addInt( a:Int = 5, b:Int = 7 ) : Int = {
var sum:Int = 0
sum = a + b
return sum
}
}
Output
Returned Value : 12
19
High-Order Functions
- Scala allows the definition of higher-order functions. These are functions that take other functions as
parameters, or whose result is a function.
Example
object Demo {
def main(args: Array[String]) {
println( apply( layout, 10) )
}
def apply(f: Int => String, v: Int) = f(v)
def layout[A](x: A) = "[" + x.toString() + "]"
}
Output
[10]
20
Nested Functions
-Scala allows you to define functions inside a function and functions defined inside other functions are called
local functions.
Example
object Demo {
def main(args: Array[String]) {
println( factorial(0) ); println( factorial(1) ); println( factorial(2) ); println( factorial(3) )
}
def factorial(i: Int): Int = {
def fact(i: Int, accumulator: Int): Int = {
if (i <= 1)
accumulator
else
fact(i - 1, i * accumulator)
}
fact(i, 1)
}
}
Output
1 1 2 6
21
Anonymous Functions
-Anonymous functions in source code are called function literals and at run time, function literals are
instantiated into objects called function values.
Example 1
var inc = (x:Int) => x+1
var x = inc(7)-1
Example 1
var mul = (x: Int, y: Int) => x*y
println(mul(3, 4))
Example 2
var userDir = () => { System.getProperty("user.dir") }
println( userDir )
22
Partially Applied Functions
-If you pass all the expected arguments, you have fully applied it. If you send only a few arguments, then you
get back a partially applied function.
Example 1
import java.util.Date
object Demo {
def main(args: Array[String]) {
val date = new Date
val logWithDateBound = log(date, _ : String)
logWithDateBound("message1" )
Thread.sleep(1000)
logWithDateBound("message2" )
Thread.sleep(1000)
logWithDateBound("message3" )
}
def log(date: Date, message: String) = { println(date + "----" + message) } }
Output
Mon Dec 02 12:53:56 CST 2013----message1
Mon Dec 02 12:53:56 CST 2013----message2
Mon Dec 02 12:53:56 CST 2013----message3
23
Currying Functions
- Currying transforms a function that takes multiple parameters into a chain of functions, each taking a single
parameter.
Example 1
object Demo {
def main(args: Array[String]) {
val str1:String = "Hello, "
val str2:String = "Scala!"
println( "str1 + str2 = " + strcat(str1)(str2) )
}
def strcat(s1: String)(s2: String) = {
s1 + s2
}
}
Output
str1 + str2 = Hello, Scala!
24
Scala – Closures
- A closure is a function, whose return value depends on the value of one or more variables declared outside
this function.
Example 1
object Demo {
def main(args: Array[String]) {
println( "multiplier(1) value = " + multiplier(1) )
println( "multiplier(2) value = " + multiplier(2) )
}
var factor = 3
val multiplier = (i:Int) => i * factor
}
Output
multiplier(1) value = 3
multiplier(2) value = 6
25
Scala – Exception Handling
- Scala allows you to try/catch any exception in a single block and then perform pattern matching against it
using case blocks.
Example 1
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException
object Demo {
def main(args: Array[String]) {
try {
val f = new FileReader("input.txt")
} catch {
case ex: FileNotFoundException =>{
println("Missing file exception")
}
case ex: IOException => {
println("IO Exception")
} } } }
Output
Missing file exception
Exiting finally...
Arrays
Arrays in Scala are parameterized types
Array[String] is an Array of Strings, where String is a type parameter
In Java we would call this a “generic type”
When no initial values are given, new is required, along with an
explicit type:
val ary = new Array[Int](5)
When initial values are given, new is not allowed:
val ary2 = Array(3, 1, 4, 1, 6)
Array syntax in Scala is just object syntax
Scala’s Lists are more useful, and used more often, than Arrays
val list1 = List(3, 1, 4, 1, 6)
val list2 = List[Int]() // An empty list must have an
explicit type
27
Scala Collections
- Scala has a rich set of collection library.
Lists Scala's List[T] is a linked list of type T.
Sets A set is a collection of pairwise different
elements of the same type.
Maps A Map is a collection of key/value pairs. Any
value can be retrieved based on its key.
Tuples Unlike an array or list, a tuple can hold
objects with different types.
Options Option[T] provides a container for zero or
one element of a given type.
Iterators An iterator is not a collection, but rather a
way to access the elements of a collection
one by one.
28
The End
Q & A

More Related Content

PDF
Programming in Scala: Notes
ODP
A Tour Of Scala
PDF
Scala : language of the future
PDF
Scala @ TechMeetup Edinburgh
PPTX
A Brief Intro to Scala
PPTX
PDF
Introduction to Functional Programming with Scala
PDF
Scala coated JVM
Programming in Scala: Notes
A Tour Of Scala
Scala : language of the future
Scala @ TechMeetup Edinburgh
A Brief Intro to Scala
Introduction to Functional Programming with Scala
Scala coated JVM

What's hot (20)

PPT
Scala Talk at FOSDEM 2009
PDF
Metaprogramming in Scala 2.10, Eugene Burmako,
PPTX
Intro to Functional Programming in Scala
PDF
Procedure Typing for Scala
PPTX
Scala fundamentals
PDF
PDF
PDF
Stepping Up : A Brief Intro to Scala
PDF
Java 8: the good parts!
PDF
Scala in Practice
PPTX
New Features in JDK 8
PDF
Scala introduction
PDF
Workshop Scala
PDF
20160520 what youneedtoknowaboutlambdas
PDF
Starting with Scala : Frontier Developer's Meetup December 2010
PDF
Introduction to Scala
PDF
scala
PDF
PPTX
Java 8 Feature Preview
PPTX
Java 8 Lambda and Streams
Scala Talk at FOSDEM 2009
Metaprogramming in Scala 2.10, Eugene Burmako,
Intro to Functional Programming in Scala
Procedure Typing for Scala
Scala fundamentals
Stepping Up : A Brief Intro to Scala
Java 8: the good parts!
Scala in Practice
New Features in JDK 8
Scala introduction
Workshop Scala
20160520 what youneedtoknowaboutlambdas
Starting with Scala : Frontier Developer's Meetup December 2010
Introduction to Scala
scala
Java 8 Feature Preview
Java 8 Lambda and Streams
Ad

Similar to Scala in a nutshell by venkat (20)

PPTX
Principles of functional progrmming in scala
PDF
PPTX
Introduction to Scala
PDF
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
PPTX
Intro to Scala
PPTX
Introduction to Scala
PPTX
Scala-Ls1
PDF
Functional programming in Scala
PDF
Scala tutorial
PDF
Scala tutorial
PDF
Scala.pdf
PDF
Short intro to scala and the play framework
ODP
Scala oo (1)
ODP
Functional Objects & Function and Closures
ODP
Functional Objects & Function and Closures
PPTX
Scala final ppt vinay
PDF
2014 holden - databricks umd scala crash course
ODP
Introduction to Scala
PDF
Introduction to Scala : Clueda
PDF
Getting Started With Scala
Principles of functional progrmming in scala
Introduction to Scala
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
Intro to Scala
Introduction to Scala
Scala-Ls1
Functional programming in Scala
Scala tutorial
Scala tutorial
Scala.pdf
Short intro to scala and the play framework
Scala oo (1)
Functional Objects & Function and Closures
Functional Objects & Function and Closures
Scala final ppt vinay
2014 holden - databricks umd scala crash course
Introduction to Scala
Introduction to Scala : Clueda
Getting Started With Scala
Ad

More from Venkateswaran Kandasamy (6)

PDF
Apache Spark Notes
PDF
Hadoop Interview Questions
PDF
PDF
Lambda Architecture
PPTX
PPT
Spark streaming
Apache Spark Notes
Hadoop Interview Questions
Lambda Architecture
Spark streaming

Recently uploaded (20)

PDF
Connector Corner: Transform Unstructured Documents with Agentic Automation
PDF
LMS bot: enhanced learning management systems for improved student learning e...
PDF
The-2025-Engineering-Revolution-AI-Quality-and-DevOps-Convergence.pdf
PDF
Introduction to MCP and A2A Protocols: Enabling Agent Communication
PPTX
SGT Report The Beast Plan and Cyberphysical Systems of Control
PDF
Transform-Your-Streaming-Platform-with-AI-Driven-Quality-Engineering.pdf
PDF
Rapid Prototyping: A lecture on prototyping techniques for interface design
PDF
Lung cancer patients survival prediction using outlier detection and optimize...
PDF
CXOs-Are-you-still-doing-manual-DevOps-in-the-age-of-AI.pdf
PDF
The-Future-of-Automotive-Quality-is-Here-AI-Driven-Engineering.pdf
PDF
5-Ways-AI-is-Revolutionizing-Telecom-Quality-Engineering.pdf
PDF
NewMind AI Weekly Chronicles – August ’25 Week IV
PDF
CEH Module 2 Footprinting CEH V13, concepts
PDF
Planning-an-Audit-A-How-To-Guide-Checklist-WP.pdf
PDF
Build Real-Time ML Apps with Python, Feast & NoSQL
PDF
zbrain.ai-Scope Key Metrics Configuration and Best Practices.pdf
PDF
“The Future of Visual AI: Efficient Multimodal Intelligence,” a Keynote Prese...
PDF
Human Computer Interaction Miterm Lesson
PDF
Auditboard EB SOX Playbook 2023 edition.
PDF
ment.tech-Siri Delay Opens AI Startup Opportunity in 2025.pdf
Connector Corner: Transform Unstructured Documents with Agentic Automation
LMS bot: enhanced learning management systems for improved student learning e...
The-2025-Engineering-Revolution-AI-Quality-and-DevOps-Convergence.pdf
Introduction to MCP and A2A Protocols: Enabling Agent Communication
SGT Report The Beast Plan and Cyberphysical Systems of Control
Transform-Your-Streaming-Platform-with-AI-Driven-Quality-Engineering.pdf
Rapid Prototyping: A lecture on prototyping techniques for interface design
Lung cancer patients survival prediction using outlier detection and optimize...
CXOs-Are-you-still-doing-manual-DevOps-in-the-age-of-AI.pdf
The-Future-of-Automotive-Quality-is-Here-AI-Driven-Engineering.pdf
5-Ways-AI-is-Revolutionizing-Telecom-Quality-Engineering.pdf
NewMind AI Weekly Chronicles – August ’25 Week IV
CEH Module 2 Footprinting CEH V13, concepts
Planning-an-Audit-A-How-To-Guide-Checklist-WP.pdf
Build Real-Time ML Apps with Python, Feast & NoSQL
zbrain.ai-Scope Key Metrics Configuration and Best Practices.pdf
“The Future of Visual AI: Efficient Multimodal Intelligence,” a Keynote Prese...
Human Computer Interaction Miterm Lesson
Auditboard EB SOX Playbook 2023 edition.
ment.tech-Siri Delay Opens AI Startup Opportunity in 2025.pdf

Scala in a nutshell by venkat

  • 1. Scala in a nutshell
  • 2. 2 Agenda  Why Scala ?  Difference b/w Java and Scala  Scala Data Types  Scala Variables  Scala Classes & Objects  Scala Functions  Scala Closures  Scala Exception Handling  Scala Collections
  • 3. 3 Java What’s wrong with Java? Not designed for highly concurrent programs • The original Thread model was just wrong (it’s been fixed) • Java 5+ helps by including java.util.concurrent Verbose • Too much of Thing thing = new Thing(); • Too much “boilerplate,” for example, getters and setters What’s right with Java? Very popular Object oriented (mostly), which is important for large projects Strong typing (more on this later) The fine large library of classes The JVM! Platform independent, highly optimized
  • 4. 4 Scala is like Java, except when it isn’t Java is a good language, and Scala is a lot like it For each difference, there is a reason--none of the changes are “just to be different” Scala and Java are (almost) completely interoperable Call Java from Scala? No problem! Call Scala from Java? Some restrictions, but mostly OK. Scala compiles to .class files (a lot of them!), and can be run with either the scala command or the java command To understand Scala, it helps to understand the reasons for the changes, and what it is Scala is trying to accomplish
  • 5. 5 Verbosity Java: class Person { private String firstName; private String lastName; private int age; public Person(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } public void setFirstName(String firstName) { this.firstName = firstName; } public void String getFirstName() { return this.firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public void String getLastName() { return this.lastName; } public void setAge(int age) { this.age = age; } public void int getAge() { return this.age; } } Scala: class Person(var firstName: String, var lastName: String, var age: Int)
  • 7. Getting Scala Download ScalaIDE: http://scala-ide.org/ This is a customized version of Eclipse Already using Eclipse? It’s okay to have more than one version Scala can also be obtained by itself: http://www.scala-lang.org/downloads You can use the Scala documentation online, http://www.scala-lang.org/downloads or download it and use it locally, http://www.scala-lang.org/downloads Documentation is not always complete or easy to read The source is directly available from the documentation
  • 8. Hello World /** Everybody's first program */ object HelloWorld { def main(args: Array[String]) { println("Hello, World!") } } Save on a file named HelloWorld.scala Compile with scalac HelloWorld.scala (or from your IDE) Run with scala HelloWorld (or from your IDE) Generate documentation with scaladoc HelloWorld.scala The above code creates a singleton object Everything in the object is like Java’s static Scala doesn’t have static Scala does have classes; we’ll get to those later 8
  • 9. 9 Scala Data Types - Scala has all the same data types as Java, with the same memory footprint and precision. – Byte 8 bit signed value. Range from -128 to – Short 16 bit signed value. Range -32768 to 32767 – Int 32 bit signed value. Range -2147483648 to 2147483647 – Long 64 bit signed value. -9223372036854775808 to 9223372036854775807 – Float 32 bit – Double 64 bit – Char 16 bit unsigned Unicode character. – String A sequence of Chars – Boolean Either the literal true or the literal false – Unit Corresponds to no value – Null null or empty reference – Nothing The subtype of every other type; includes no values – Any The supertype of any type; any object is of type Any – AnyRef The supertype of any reference type
  • 10. 10 Scala variables – Variables are nothing but reserved memory locations to store values. This means that when you create a variable, you reserve some space in memory. – Types of Variables : Var ( mutable variable) , Val (immutable variable) Example object Demo { def main(args: Array[String]) { var myVar :Int = 10; val myVal :String = "Hello Scala with datatype declaration."; var myVar1 = 20; val myVal1 = "Hello Scala new without datatype declaration."; println(myVar); println(myVal); println(myVar1); println(myVal1); } } Output 10 Hello Scala with datatype declaration. 20 Hello Scala without datatype declaration.
  • 11. 11 Scala Classes & Objects Basic Class Example import java.io._ class Point(val xc: Int, val yc: Int) { var x: Int = xc var y: Int = yc def move(dx: Int, dy: Int) { x = x + dx y = y + dy println ("Point x location : " + x) println ("Point y location : " + y) } } object Demo { def main(args: Array[String]) { val pt = new Point(10, 20) pt.move(10, 10) } }
  • 12. 12 Scala Functions - A function is a group of statements that perform a task. - A Scala method is a part of a class which has a name, a signature, optionally some annotations, and some bytecode - A function in Scala is a complete object which can be assigned to a variable. - A function definition can appear anywhere in a source file and Scala permits nested function definitions, that is, function definitions inside other function definitions. - Scala function's name can have characters like +, ++, ~, &,-, --, , /, :, etc. Function Declarations def functionName ([list of parameters]) : [return type] Function Definitions def functionName ([list of parameters]) : [return type] = { function body return [expr] }
  • 13. 13 Scala Functions cont. Example object Demo { def main(args: Array[String]) { println( "Returned Value : " + addInt(5,7) ); } def addInt( a:Int, b:Int ) : Int = { var sum:Int = 0 sum = a + b return sum } } Types of Scala Functions Functions Call-by-Name Functions with Named Arguments Function with Variable Arguments Recursion Functions Default Parameter Values Higher-Order Functions Nested Functions Anonymous Functions
  • 14. 14 Functions Call-by-Name - A call-by-name mechanism passes a code block to the call and each time the call accesses the parameter, the code block is executed and the value is calculated. Example object Demo { def main(args: Array[String]) { delayed(time()); } def time() = { println("Getting time in nano seconds") System.nanoTime } def delayed( t: => Long ) = { println("In delayed method") println("Param: " + t) } } Output In delayed method Getting time in nano seconds Param: 2027245119786400
  • 15. 15 Functions with Named Arguments - Named arguments allow you to pass arguments to a function in a different order. Example object Demo { def main(args: Array[String]) { printInt(b = 5, a = 7); } def printInt( a:Int, b:Int ) = { println("Value of a : " + a ); println("Value of b : " + b ); } } Output Value of a : 7 Value of b : 5
  • 16. 16 Functions with Variable Arguments - Scala allows you to indicate that the last parameter to a function may be repeated. This allows clients to pass variable length argument lists to the function. Example object Demo { def main(args: Array[String]) { printStrings("Hello", "Scala", "Python"); } def printStrings( args:String* ) = { var i : Int = 0; for( arg <- args ){ println("Arg value[" + i + "] = " + arg ); i = i + 1; } } } Output Arg value[0] = Hello Arg value[1] = Scala Arg value[2] = Python
  • 17. 17 Recursion Functions - Recursion plays a big role in pure functional programming and Scala supports recursion functions very well. Recursion means a function can call itself repeatedly. Example object Demo { def main(args: Array[String]) { for (i <- 1 to 4) println( "Factorial of " + i + ": = " + factorial(i) ) } def factorial(n: BigInt): BigInt = { if (n <= 1) 1 else n * factorial(n - 1) } } Output Factorial of 1: = 1 Factorial of 2: = 2 Factorial of 3: = 6 Factorial of 4: = 24
  • 18. 18 Default Parameter values for a Function - Scala lets you specify default values for function parameters. Example object Demo { def main(args: Array[String]) { println( "Returned Value : " + addInt() ); } def addInt( a:Int = 5, b:Int = 7 ) : Int = { var sum:Int = 0 sum = a + b return sum } } Output Returned Value : 12
  • 19. 19 High-Order Functions - Scala allows the definition of higher-order functions. These are functions that take other functions as parameters, or whose result is a function. Example object Demo { def main(args: Array[String]) { println( apply( layout, 10) ) } def apply(f: Int => String, v: Int) = f(v) def layout[A](x: A) = "[" + x.toString() + "]" } Output [10]
  • 20. 20 Nested Functions -Scala allows you to define functions inside a function and functions defined inside other functions are called local functions. Example object Demo { def main(args: Array[String]) { println( factorial(0) ); println( factorial(1) ); println( factorial(2) ); println( factorial(3) ) } def factorial(i: Int): Int = { def fact(i: Int, accumulator: Int): Int = { if (i <= 1) accumulator else fact(i - 1, i * accumulator) } fact(i, 1) } } Output 1 1 2 6
  • 21. 21 Anonymous Functions -Anonymous functions in source code are called function literals and at run time, function literals are instantiated into objects called function values. Example 1 var inc = (x:Int) => x+1 var x = inc(7)-1 Example 1 var mul = (x: Int, y: Int) => x*y println(mul(3, 4)) Example 2 var userDir = () => { System.getProperty("user.dir") } println( userDir )
  • 22. 22 Partially Applied Functions -If you pass all the expected arguments, you have fully applied it. If you send only a few arguments, then you get back a partially applied function. Example 1 import java.util.Date object Demo { def main(args: Array[String]) { val date = new Date val logWithDateBound = log(date, _ : String) logWithDateBound("message1" ) Thread.sleep(1000) logWithDateBound("message2" ) Thread.sleep(1000) logWithDateBound("message3" ) } def log(date: Date, message: String) = { println(date + "----" + message) } } Output Mon Dec 02 12:53:56 CST 2013----message1 Mon Dec 02 12:53:56 CST 2013----message2 Mon Dec 02 12:53:56 CST 2013----message3
  • 23. 23 Currying Functions - Currying transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. Example 1 object Demo { def main(args: Array[String]) { val str1:String = "Hello, " val str2:String = "Scala!" println( "str1 + str2 = " + strcat(str1)(str2) ) } def strcat(s1: String)(s2: String) = { s1 + s2 } } Output str1 + str2 = Hello, Scala!
  • 24. 24 Scala – Closures - A closure is a function, whose return value depends on the value of one or more variables declared outside this function. Example 1 object Demo { def main(args: Array[String]) { println( "multiplier(1) value = " + multiplier(1) ) println( "multiplier(2) value = " + multiplier(2) ) } var factor = 3 val multiplier = (i:Int) => i * factor } Output multiplier(1) value = 3 multiplier(2) value = 6
  • 25. 25 Scala – Exception Handling - Scala allows you to try/catch any exception in a single block and then perform pattern matching against it using case blocks. Example 1 import java.io.FileReader import java.io.FileNotFoundException import java.io.IOException object Demo { def main(args: Array[String]) { try { val f = new FileReader("input.txt") } catch { case ex: FileNotFoundException =>{ println("Missing file exception") } case ex: IOException => { println("IO Exception") } } } } Output Missing file exception Exiting finally...
  • 26. Arrays Arrays in Scala are parameterized types Array[String] is an Array of Strings, where String is a type parameter In Java we would call this a “generic type” When no initial values are given, new is required, along with an explicit type: val ary = new Array[Int](5) When initial values are given, new is not allowed: val ary2 = Array(3, 1, 4, 1, 6) Array syntax in Scala is just object syntax Scala’s Lists are more useful, and used more often, than Arrays val list1 = List(3, 1, 4, 1, 6) val list2 = List[Int]() // An empty list must have an explicit type
  • 27. 27 Scala Collections - Scala has a rich set of collection library. Lists Scala's List[T] is a linked list of type T. Sets A set is a collection of pairwise different elements of the same type. Maps A Map is a collection of key/value pairs. Any value can be retrieved based on its key. Tuples Unlike an array or list, a tuple can hold objects with different types. Options Option[T] provides a container for zero or one element of a given type. Iterators An iterator is not a collection, but rather a way to access the elements of a collection one by one.