SlideShare a Scribd company logo
Scala training workshop 01
Nguyen Thanh Tuan
Platform Department
@Septeni Technology
Agenda
- Summary
- Functions & Evaluations
- Higher Order Functions
- Data and Abstraction
- Exercise
- Share
Functions & Evaluations
- Conditionals and Value Definitions
- Blocks
- Tail recursion
Conditional and Value Definition
- Sample :
val <identifier>[: <type>] = <expression>
var <identifier>[: <type>] = <expression>
- If Expressions
if (<Boolean expression>) <expression>
- If-Else Expressions
if (<Boolean expression>) <expression>
else <expression>
- Match Expressions
<expression> match {
case <pattern match> => <expression>
[case...]
}
- A Pattern Alternative :
case <pattern 1> | <pattern 2> .. => <one or more expressions>
- Matching with Wildcard Patterns
case <identifier> => <one or more expressions>
- Matching with Pattern Guards
case <pattern> if <Boolean expression> => <one or more
expressions>
- Match Expressions
<expression> match {
case <pattern match> => <expression>
[case...]
}
Source : Safaribooksonline.com
Example
- If Expressions
if (10%2 == 0) println(“10 is a multiple of 2”)
- If-Else Expressions
val x = 10;
val y = 5
if (x > y) println(“Max number is :”+ x)
else println(“Max numner is :” + y)
- Match Expressions
val x = 10;
val y = 5;
val max = x > y match {
case true => x
case true => y
}
- A Pattern Alternative :
val day = “MON”
val kind = day match {
case “MON”| ”TUE” | “WED” | “THU” | “FRI”
=>
“weekday”
case “SAT” | “SUN” =>
“weekend”
}
- Matching with Wildcard Patterns
case _ => {println(s”Couldn’t parse $message”) -1}
- Matching with Pattern Guards
case 3 if 3 > 5=> println(“Something”)
Source : Safaribooksonline.com
Blocks
val x = 0
def f(y: Int) = y + 1
val result = {
val x = f(3)
x * x
} + x
- A block is delimited by braces { ...
}
- It contains a sequence of
definitions or expressions
- Blocks are themselves
expressions; a block may appear
everywhere an expression can
- The definitions inside a block are
only visible from within the block.
Tail recursion
- Recursion definition : A call B, B call A ..etc
- Reasons we don’t see alot of recursion code in Java
- is hard ( is not intuitive : you see one layer and you have to
imagine what happens when those layers stack up)
- is not designed to accommodate recursion. It’s designed to
accommodate iteration.
- But in Scala, being a function language is very much geared toward
recursion rather than iteration ( Scala in the case of tail recursive,
can eliminate the creation of a new stack frame and just re-use the
current stack frame)
Example
def pascal(c: Int, r: Int): Int = {
if(c == 0) return 1
if(c == 1 && c != r) return r
if(c == r) return 1
pascal(c-1,r-1)+pascal(c,r-1)
}
Tail&Head recursion in Scala
def listLength2(list: List[_]): Int =
{
def listLength2Helper(list: List[_],
len: Int): Int = {
if (list == Nil) len
else listLength2Helper(list.tail,
len + 1)
}
listLength2Helper(list, 0)
}
var list1 = List(1, 2, 3, 4, 5, 6, 7,
8, 9, 10)
println( listLength2( list1 ) )
def listLength1(list: List[_]): Int =
{
if (list == Nil) 0
else 1 + listLength1(list.tail)
}
var list1 = List(1, 2, 3, 4, 5, 6, 7,
8, 9, 10)
println( listLength1( list1 ) )
Higher-order function
- Higher Order Functions
- Currying
Higher-order function
Scala allows the definition of higher-order
functions.
- Functions can take other functions as
parameters
- Result is a function
- Example
Example higherOrder
object higherOrder {
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() + "]
}
Currying Functions
Currying transforms a function that takes
multiple parameters into a chain of function,
each taking a single parameter. Curried
functions are defined with multiple parameter
lists, as follows :
def strcat(s1: String)(s2: String) = s1 + s2
OR
def strcat(s1: String) = (s2: String) => s1 + s2
Example Currying functions
object Currying {
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
}
}
Data and Abstraction
- Class hierarchy
- Trait and Abstractclass
Class hierarchy
Source : meetfp.com
Trait and Abstract class
- Scala has traits, and a trait is more flexible than an abstract class, so you
wonder, “When should I use an abstract class?”
- Reason is :
- You want to create a base class that requires constructor arguments
- The code will be called from Java code
- We can use
abstract class Animal(name: String)
- But we can’t use
trait Animal(name: String)
Trait ( The reason we should use trait )
- One big advantage of traits is that you can extend multiple traits but only
one abstract class. Traits solve many of the problems with multiple
inheritance but allow code reuse.
- Define types by specifying the signatures of supported methods.
This is similar to how interfaces work in Java.
But trait can’t
- Traits do not have constructor parameters (but this should not be an issue in practice).
- Traits impose a slight performance overhead (but this is unlikely to impact the overall
performance of your program)
- Traits introduce compilation fragility for classes that mix them in. If a trait changes, a class that
mixes it in has to be recompiled
Exercises
- Pascal’s Triangle
The following pattern of numbers is called Pascal’s triangle.
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
...
The numbers at the edge of the triangle are all 1, and each number inside the triangle is the sum of the two numbers above it. Write a function
that computes the elements of Pascal’s triangle by means of a recursive process.
Do this exercise by implementing the pascal function in Main.scala, which takes a column c and a row r, counting from 0 and returns the number
at that spot in the triangle. For example: pascal(0,2)=1, pascal(1,2)=2 and pascal(1,3)=3.
def pascal(c: Int, r: Int): Int
Source : coursera.org
Exercises
object Main {
def main(args: Array[String]) {
println("Pascal's Triangle")
for (row <- 0 to 10) {
for (col <- 0 to row)
print(pascal(col, row) + " ")
println()
}
def pascal(c: Int, r: Int): Int = {
c match {
case 0 => 1
case 1 if c == 1 && c != r => r
case r => 1
case _ => pascal(c-1,r-1)+pascal(c,r-1)
}
}
}
Shares
Thank for comming

More Related Content

PPTX
An Introduction to Scala
PPTX
Introduction to Scala
PPTX
Scala, Play 2.0 & Cloud Foundry
PPT
Scala Talk at FOSDEM 2009
PDF
An Introduction to Scala for Java Developers
PPTX
The Evolution of Scala
PDF
Solid and Sustainable Development in Scala
PDF
A Scala tutorial
An Introduction to Scala
Introduction to Scala
Scala, Play 2.0 & Cloud Foundry
Scala Talk at FOSDEM 2009
An Introduction to Scala for Java Developers
The Evolution of Scala
Solid and Sustainable Development in Scala
A Scala tutorial

What's hot (11)

PDF
A Brief, but Dense, Intro to Scala
PPTX
Practical type mining in Scala
ODP
Refactoring to Scala DSLs and LiftOff 2009 Recap
PDF
camel-scala.pdf
PDF
Simplicitly
PDF
Android course session 5 (Threads & socket)
PPTX
Java 201 Intro to Test Driven Development in Java
PDF
Miles Sabin Introduction To Scala For Java Developers
PPTX
Java 102 intro to object-oriented programming in java
PPTX
Java 101 Intro to Java Programming - Exercises
PPTX
Scale up your thinking
A Brief, but Dense, Intro to Scala
Practical type mining in Scala
Refactoring to Scala DSLs and LiftOff 2009 Recap
camel-scala.pdf
Simplicitly
Android course session 5 (Threads & socket)
Java 201 Intro to Test Driven Development in Java
Miles Sabin Introduction To Scala For Java Developers
Java 102 intro to object-oriented programming in java
Java 101 Intro to Java Programming - Exercises
Scale up your thinking
Ad

Similar to Scala basic (20)

PPTX
Scala training workshop 02
PDF
Introductiontoprogramminginscala
PDF
Introduction to Scala for JCConf Taiwan
PDF
Programming in Scala: Notes
PPTX
Intro to Scala
ODP
PDF
Programming in Scala - Lecture Three
PDF
Scala Quick Introduction
PDF
From Java to Scala - advantages and possible risks
PPTX
Scala for curious
PPTX
Principles of functional progrmming in scala
PPTX
Scala Introduction
PPTX
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
PDF
Programming in scala - 1
PDF
Functional programming ii
PDF
Meet scala
PDF
Introduction to programming in scala
PPTX
Introduction to Scala
PDF
Scala for Java Developers (Silicon Valley Code Camp 13)
ODP
Effective way to code in Scala
Scala training workshop 02
Introductiontoprogramminginscala
Introduction to Scala for JCConf Taiwan
Programming in Scala: Notes
Intro to Scala
Programming in Scala - Lecture Three
Scala Quick Introduction
From Java to Scala - advantages and possible risks
Scala for curious
Principles of functional progrmming in scala
Scala Introduction
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Programming in scala - 1
Functional programming ii
Meet scala
Introduction to programming in scala
Introduction to Scala
Scala for Java Developers (Silicon Valley Code Camp 13)
Effective way to code in Scala
Ad

Recently uploaded (20)

PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
cuic standard and advanced reporting.pdf
PDF
Advanced Soft Computing BINUS July 2025.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Transforming Manufacturing operations through Intelligent Integrations
PDF
Empathic Computing: Creating Shared Understanding
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
PPTX
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Electronic commerce courselecture one. Pdf
cuic standard and advanced reporting.pdf
Advanced Soft Computing BINUS July 2025.pdf
Review of recent advances in non-invasive hemoglobin estimation
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
MYSQL Presentation for SQL database connectivity
Transforming Manufacturing operations through Intelligent Integrations
Empathic Computing: Creating Shared Understanding
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
CIFDAQ's Market Insight: SEC Turns Pro Crypto
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Chapter 3 Spatial Domain Image Processing.pdf
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
“AI and Expert System Decision Support & Business Intelligence Systems”
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
Per capita expenditure prediction using model stacking based on satellite ima...

Scala basic

  • 1. Scala training workshop 01 Nguyen Thanh Tuan Platform Department @Septeni Technology
  • 2. Agenda - Summary - Functions & Evaluations - Higher Order Functions - Data and Abstraction - Exercise - Share
  • 3. Functions & Evaluations - Conditionals and Value Definitions - Blocks - Tail recursion
  • 4. Conditional and Value Definition - Sample : val <identifier>[: <type>] = <expression> var <identifier>[: <type>] = <expression> - If Expressions if (<Boolean expression>) <expression> - If-Else Expressions if (<Boolean expression>) <expression> else <expression> - Match Expressions <expression> match { case <pattern match> => <expression> [case...] } - A Pattern Alternative : case <pattern 1> | <pattern 2> .. => <one or more expressions> - Matching with Wildcard Patterns case <identifier> => <one or more expressions> - Matching with Pattern Guards case <pattern> if <Boolean expression> => <one or more expressions> - Match Expressions <expression> match { case <pattern match> => <expression> [case...] } Source : Safaribooksonline.com
  • 5. Example - If Expressions if (10%2 == 0) println(“10 is a multiple of 2”) - If-Else Expressions val x = 10; val y = 5 if (x > y) println(“Max number is :”+ x) else println(“Max numner is :” + y) - Match Expressions val x = 10; val y = 5; val max = x > y match { case true => x case true => y } - A Pattern Alternative : val day = “MON” val kind = day match { case “MON”| ”TUE” | “WED” | “THU” | “FRI” => “weekday” case “SAT” | “SUN” => “weekend” } - Matching with Wildcard Patterns case _ => {println(s”Couldn’t parse $message”) -1} - Matching with Pattern Guards case 3 if 3 > 5=> println(“Something”) Source : Safaribooksonline.com
  • 6. Blocks val x = 0 def f(y: Int) = y + 1 val result = { val x = f(3) x * x } + x - A block is delimited by braces { ... } - It contains a sequence of definitions or expressions - Blocks are themselves expressions; a block may appear everywhere an expression can - The definitions inside a block are only visible from within the block.
  • 7. Tail recursion - Recursion definition : A call B, B call A ..etc - Reasons we don’t see alot of recursion code in Java - is hard ( is not intuitive : you see one layer and you have to imagine what happens when those layers stack up) - is not designed to accommodate recursion. It’s designed to accommodate iteration. - But in Scala, being a function language is very much geared toward recursion rather than iteration ( Scala in the case of tail recursive, can eliminate the creation of a new stack frame and just re-use the current stack frame)
  • 8. Example def pascal(c: Int, r: Int): Int = { if(c == 0) return 1 if(c == 1 && c != r) return r if(c == r) return 1 pascal(c-1,r-1)+pascal(c,r-1) }
  • 9. Tail&Head recursion in Scala def listLength2(list: List[_]): Int = { def listLength2Helper(list: List[_], len: Int): Int = { if (list == Nil) len else listLength2Helper(list.tail, len + 1) } listLength2Helper(list, 0) } var list1 = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) println( listLength2( list1 ) ) def listLength1(list: List[_]): Int = { if (list == Nil) 0 else 1 + listLength1(list.tail) } var list1 = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) println( listLength1( list1 ) )
  • 10. Higher-order function - Higher Order Functions - Currying
  • 11. Higher-order function Scala allows the definition of higher-order functions. - Functions can take other functions as parameters - Result is a function - Example
  • 12. Example higherOrder object higherOrder { 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() + "] }
  • 13. Currying Functions Currying transforms a function that takes multiple parameters into a chain of function, each taking a single parameter. Curried functions are defined with multiple parameter lists, as follows : def strcat(s1: String)(s2: String) = s1 + s2 OR def strcat(s1: String) = (s2: String) => s1 + s2
  • 14. Example Currying functions object Currying { 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 } }
  • 15. Data and Abstraction - Class hierarchy - Trait and Abstractclass
  • 17. Trait and Abstract class - Scala has traits, and a trait is more flexible than an abstract class, so you wonder, “When should I use an abstract class?” - Reason is : - You want to create a base class that requires constructor arguments - The code will be called from Java code - We can use abstract class Animal(name: String) - But we can’t use trait Animal(name: String)
  • 18. Trait ( The reason we should use trait ) - One big advantage of traits is that you can extend multiple traits but only one abstract class. Traits solve many of the problems with multiple inheritance but allow code reuse. - Define types by specifying the signatures of supported methods. This is similar to how interfaces work in Java. But trait can’t - Traits do not have constructor parameters (but this should not be an issue in practice). - Traits impose a slight performance overhead (but this is unlikely to impact the overall performance of your program) - Traits introduce compilation fragility for classes that mix them in. If a trait changes, a class that mixes it in has to be recompiled
  • 19. Exercises - Pascal’s Triangle The following pattern of numbers is called Pascal’s triangle. 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 ... The numbers at the edge of the triangle are all 1, and each number inside the triangle is the sum of the two numbers above it. Write a function that computes the elements of Pascal’s triangle by means of a recursive process. Do this exercise by implementing the pascal function in Main.scala, which takes a column c and a row r, counting from 0 and returns the number at that spot in the triangle. For example: pascal(0,2)=1, pascal(1,2)=2 and pascal(1,3)=3. def pascal(c: Int, r: Int): Int Source : coursera.org
  • 20. Exercises object Main { def main(args: Array[String]) { println("Pascal's Triangle") for (row <- 0 to 10) { for (col <- 0 to row) print(pascal(col, row) + " ") println() } def pascal(c: Int, r: Int): Int = { c match { case 0 => 1 case 1 if c == 1 && c != r => r case r => 1 case _ => pascal(c-1,r-1)+pascal(c,r-1) } } }

Editor's Notes

  • #5: https://www.safaribooksonline.com/library/view/learning-scala/9781449368814/ch03.html
  • #7: http://lamp.epfl.ch/files/content/sites/lamp/files/teaching/progfun/slides/week1-6-no-annot.pdf
  • #8: There are two basic kinds of recursive: head recursive and tail recursive. In head recursion and tail recursion. In head recursion, a function makes its recursive call and then performs some more calculations, maybe using the result of the recursive call. In a tail recursive function, all calculations happen first and the recursive call is the last thing that happens This won’t work with head recursive. Because : First it does some work, then it makes its recursive call, then it does a little more work. We can’t just re-use the current stack frame when we make that recursive call. We’re going to NEED that stack frame into after the recursive call completes
  • #10: http://oldfashionedsoftware.com/2008/09/27/tail-recursion-basics-in-scala/
  • #17: http://meetfp.com/en/scala-basic/class-hierarchy http://www.artima.com/pins1ed/scalas-hierarchy.html Any is the top class, which means, every other class inherits from Any, therefor every object can invoke methods provided by Any. Those methods are as following. Null is a subtype of all reference type, and Nothing is a subtype of all other classes The root class Any has two subclasses: AnyVal and AnyRef. AnyVal is the parent class of every built-in value class in Scala. There are nine such value classes: Byte,Short, Char, Int, Long, Float, Double, Boolean, and Unit. The first eight of these correspond to Java's primitive types, and their values are represented at run time as Java's primitive values. The instances of these classes are all written as literals in Scala. For example, 42 is an instance of Int, 'x' is an instance of Char, and false an instance ofBoolean. You cannot create instances of these classes using new. This is enforced by the "trick" that value classes are all defined to be both abstract and final The other subclass of the root class Any is class AnyRef. This is the base class of all reference classes in Scala. As mentioned previously, on the Java platform AnyRef is in fact just an alias for class java.lang.Object. So classes written in Java as well as classes written in Scala all inherit from AnyRef.[1] One way to think of java.lang.Object, therefore, is as the way AnyRef is implemented on the Java platform. Thus, although you can use Object and AnyRef interchangeably in Scala programs on the Java platform, the recommended style is to use AnyRef everywhere. Class Null is the type of the null reference; it is a subclass of every reference class (i.e., every class that itself inherits from AnyRef). Null is not compatible with value types.You cannot, for example, assign a null value to an integer variable: scala> val i: Int = null <console>:4: error: type mismatch; found : Null(null) required: Int Type Nothing is at the very bottom of Scala's class hierarchy; it is a subtype of every other type. However, there exist no values of this type whatsoever. Why does it make sense to have a type without values? As discussed in Section 7.4, one use of Nothing is that it signals abnormal termination. For instance there's the error method in thePredef object of Scala's standard library, which is defined like this: def error(message: String): Nothing = throw new RuntimeException(message)
  • #18: If you plan to distribute it in compiled form, and you expect outside groups to write classes inheriting from it, you might lean towards using an abstract class. The issue is that when a trait gains or loses a member, any classes that inherit from it must be recompiled, even if they have not changed. If outside clients will only call into the behavior, instead of inheriting from it, then using a trait is fine.
  • #19: http://alvinalexander.com/scala/scala-trait-examples