SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako,
Vasil Remeniuk
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
Shai Yallin
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala
akuklev
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
Alfonso Ruzafa
 
Scala test
Scala testScala test
Scala test
Inphina Technologies
 
Scala
ScalaScala
Scala
Sven Efftinge
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
Derek Chen-Becker
 
Java 8: the good parts!
Java 8: the good parts!Java 8: the good parts!
Java 8: the good parts!
Andrzej Grzesik
 
Scala in Practice
Scala in PracticeScala in Practice
Scala in Practice
Francesco Usai
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
Martin Toshev
 
Scala introduction
Scala introductionScala introduction
Scala introduction
vito jeng
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
Bert Van Vreckem
 
20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas
shinolajla
 
Starting with Scala : Frontier Developer's Meetup December 2010
Starting with Scala : Frontier Developer's Meetup December 2010Starting with Scala : Frontier Developer's Meetup December 2010
Starting with Scala : Frontier Developer's Meetup December 2010
Derek Chen-Becker
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Saleem Ansari
 
scala
scalascala
scala
Pranav E K
 
Java8
Java8Java8
Java8
Felipe Mamud
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
Jim Bethancourt
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
Venkata Naga Ravi
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako,
Vasil Remeniuk
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
Shai Yallin
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala
akuklev
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
Derek Chen-Becker
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
Martin Toshev
 
Scala introduction
Scala introductionScala introduction
Scala introduction
vito jeng
 
20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas
shinolajla
 
Starting with Scala : Frontier Developer's Meetup December 2010
Starting with Scala : Frontier Developer's Meetup December 2010Starting with Scala : Frontier Developer's Meetup December 2010
Starting with Scala : Frontier Developer's Meetup December 2010
Derek Chen-Becker
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Saleem Ansari
 

Similar to Scala in a nutshell by venkat (20)

Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
Isaias Barroso
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
Michael Stal
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
Michael Stal
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
Łukasz Wójcik
 
Scala - just good for Java shops?
Scala - just good for Java shops?Scala - just good for Java shops?
Scala - just good for Java shops?
Sarah Mount
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Xebia IT Architects
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
Eric Pederson
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
Tim (dev-tim) Zadorozhniy
 
Scala intro for Java devs 20150324
Scala intro for Java devs 20150324Scala intro for Java devs 20150324
Scala intro for Java devs 20150324
Erik Schmiegelow
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
Łukasz Bałamut
 
Scala presentationjune112011
Scala presentationjune112011Scala presentationjune112011
Scala presentationjune112011
PrasannaKumar Sathyanarayanan
 
Scala
ScalaScala
Scala
Andreas Enbohm
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
Alf Kristian Støyle
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
league
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
Joe Zulli
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
Miles Sabin
 
Scala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuScala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on Heroku
Havoc Pennington
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
daewon jeong
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
Isaias Barroso
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
Michael Stal
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
Michael Stal
 
Scala - just good for Java shops?
Scala - just good for Java shops?Scala - just good for Java shops?
Scala - just good for Java shops?
Sarah Mount
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
Eric Pederson
 
Scala intro for Java devs 20150324
Scala intro for Java devs 20150324Scala intro for Java devs 20150324
Scala intro for Java devs 20150324
Erik Schmiegelow
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
league
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
Joe Zulli
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
Miles Sabin
 
Scala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuScala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on Heroku
Havoc Pennington
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
daewon jeong
 
Ad

More from Venkateswaran Kandasamy (6)

Apache Spark Notes
Apache Spark NotesApache Spark Notes
Apache Spark Notes
Venkateswaran Kandasamy
 
Hadoop Interview Questions
Hadoop Interview QuestionsHadoop Interview Questions
Hadoop Interview Questions
Venkateswaran Kandasamy
 
Hadoop YARN
Hadoop YARN Hadoop YARN
Hadoop YARN
Venkateswaran Kandasamy
 
Lambda Architecture
Lambda ArchitectureLambda Architecture
Lambda Architecture
Venkateswaran Kandasamy
 
Hive training
Hive trainingHive training
Hive training
Venkateswaran Kandasamy
 
Spark streaming
Spark streamingSpark streaming
Spark streaming
Venkateswaran Kandasamy
 
Ad

Recently uploaded (20)

HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 

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.