9. IMUTABILIDADE
• Thread Safety
• Sem efeitos colaterais
• Previne referência a null
• Evita acoplamento temporal
• O código se torna mais simples e mais fácil de testar
9
10. FIZZBUZZ - OO
10
def fizzBuzz(number: Int) = {
var result = “"
if (number % 3 == 0 && number % 5 == 0)
result = “fizzBuzz"
if (number % 3 == 0)
result = “fizz"
if (number % 5 == 0)
result = “buzz"
else result
}
11. FIZZBUZZ - FUNCIONAL
11
def fizzBuzz(number:Int) = (number % 3, number % 5) match {
case (0, 0) => 'fizzBuzz
case (0, _) => 'fizz
case (_, 0) => 'buzz
case _ => number
}
12. FUNÇÕES DE ALTA ORDEM (HIGH ORDER FUNCTIONS)
São funções que:
• Recebem uma função como parâmetro
• Retorna uma função
Exemplo:
12
def trataErro = {
//tratamento de erro...
}
def lerArquivo(caminho, tratamentoErro) = {
//leitura do arquivo
}
lerArquivo("texto.txt", trataErro)
16. REFATORANDO…
16
def printUpTo(limit: Int): Unit = {
(0 to limit).foreach(println _)
}
def printUpTo(limit: Int): Unit = {
var i = 0
while (i <= limit) {
println("i = " + i)
i += 1
}
}
def printUpTo(limit: Int): Unit = {
(0 to limit).foreach(println)
}