Introduction to Scala
David Venturi
Curriculum Manager, DataCamp
Scala is functional
Scala usually is functional but can also be imperative sometimes
Scala is functional:
Imperative (English):
Scala usually is functional but can also be imperative sometimes
Scala can be imperative:
// Define counter variable
var i = 0
// Initialize array with each player's hand
var hands = Array(17, 24, 21)
// Loop through hands and see if each busts
while (i < hands.length) {
println(bust(hands(i)))
i = i + 1
}
// Define counter variable
var i = 0
// Initialize array with each player's hand
var hands = Array(17, 24, 21)
// Loop through hands and see if each busts
while (i < hands.length) {
println(bust(hands(i)))
i = i + 1
}
Scala usually is functional but can also be imperative sometimes
Scala is functional:
// Define counter variable
var i = 0
// Initialize array with each player's hand
var hands = Array(17, 24, 21)
// Loop through hands and see if each busts
while(i < hands.length) {
println(bust(hands(i)))
i += 1
}
// Initialize array with each player's hand
var hands = Array(17, 24, 21)
// See if each hand busts
hands.foreach(INSERT FUNCTION HERE)
// Initialize array with each player's hand
var hands = Array(17, 24, 21)
// See if each hand busts
hands.foreach(INSERT FUNCTION HERE)
From Chapter 1:
Scala combines object-oriented and functional programming
// Define a function to determine if hand busts
def bust(hand: Int) = {
println(hand > 21)
}
// Initialize array with each player's hand
var hands = Array(17, 24, 21)
// See if each hand busts
hands.foreach(INSERT FUNCTION HERE)
// Initialize array with each player's hand
var hands = Array(17, 24, 21)
// See if each hand busts
hands.foreach(bust)
false
true
false
Scala usually is functional but can also be imperative sometimes
Scala is functional:
Side effect: code that modifies some variable outside of its local scope
def bust(hand: Int) = {
println(hand > 21)
}
scala> val myHand = bust(22)
true
myHand: Unit = ()
// Define counter variable var i = 0
// Initialize array with each player's hand var hands = Array(17, 24, 21)
// Loop through hands and see if each busts while (i < hands.length) { println(bust(hands(i))) i = i + 1 }
Less functional than before
// Define a function to determine if hand busts
def bust(hand: Int) = {
println(hand > 21)
}
More functional than before
// Initialize array with each player's hand
var hands = Array(17, 24, 21)
// See if each hand busts
hands.foreach(bust)
var
Unit
val
Unit
value typesInt
Boolean
Double
Introduction to Scala