7. 7
PROS CONS
Primitivas de concurrencia
Desarrollado por Google
Tiempo de compilación
Lenguaje compilado
Lenguaje tipado
Sintaxis old style
Demasiado imperativo
Poco funcional
Inmutabilidad
11. Programacion funcional
FUNCIONES Y MAS FUNCIONES INMUTABILIDAD
CURRYING CLOSURES
LAZY EVALUATION PATTERN MATCHING
CAMBIA LA MANERA EN COMO
PROGRAMAS
12. Scala Variables?
12
val labels = Set(“")
val labels = Set[String](“”)
var labels = Set[String](“”)
Y los tipos?
Colecciones Inmutables
Syntaxis para generics <?>
NO HAY ; :D
Que es val ?
13. Scala OOP + FP
13
No es la OOP el demonio?
Un buen programador de scala no usa
side efect
Funciones puras
Usa OOP para abstraer datos
class Rational(x: Int, y: Int) {
def this(x: Int) = this(x, 1)
private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
private val g = gcd(x, y)
def numer = x / g
def denom = y / g
def < (o: Rational) = numer * o.denom < o.numer * denom
def > (o: Rational) = !(this < o)
def +(o: Rational) = {
new Rational(numer * o.denom + denom * o.numer, denom * o.denom)
}
def -(o: Rational) = {
this + (-o)
}
def unary_- = Rational(-numer, denom)
override def toString = {
numer + "/" + denom
}
} Cada cambio de estado genera un
nuevo objeto
14. Scala OOP
14
Case class -> get, set, constructor auto
Traits son similares a los modulos
en Ruby
Generic clases/traits
Singleton Object
case class SocialNetwork(id: String, name: String)
trait LinkedList[+A] {
def isEmpty: Boolean
def head: A
def tail: LinkedList[A]
def at(index: Int): A
def prepend[B >: A](elem: B): LinkedList[B] =
new Cons(elem, this)
}
object Nil extends LinkedList[Nothing] {
class Cons[A](val head: A, val tail: LinkedList[A]) extends LinkedList[A] {
15. Scala Functions
15
Toda funciona debe tener un tipo de
retorno(type inference)
Funciones como parámetros
Retorna funciones
Vector.fill(queens.length)("* “)
.updated(col, "X ").mkString
def lambda = (x: Int) => x + 1
val multiplier = (i:Int) => i * 10
def sumComp(a: Int): (Int) => Int = {
def sum(b: Int) = a + b
}
val fun = sumComp(5)
fun(1)
def sumComp(a: Int)(b: Int): Int = {
a + b
}
Currying
16. Pattern Matching
16
Es un Super Switchval secondElement = List(1,2,3) match {
case x :: y :: xs => y
case _ => 0
}
val foodItem = "porridge"
def goldilocks(expr: Any) = expr match {
case (`foodItem`, _) => "eating"
case ("chair", "Mama") => "sitting"
case ("bed", "Baby") => "sleeping"
case _ => "what?"
}
goldilocks(("porridge", "Papa"))
Compara y extrae al mismo tiempo
17. Implicits
17
Parametros inyectados en un metodo
o constructor de manera implicita
Sirve para realizar conversiones
automaticas
implicit def implChange(str:String):Int =
new Integer(str)
def sum(a:Int, b:Int):Int = a +b
sum("1", 2)
18. Monads
18
map, flatMap, filter
for comprehension
def readAsync(): Future[Option[List[String]]] =
Future { readFile() }
def readFile(): Option[List[String]] =
Try { Source.fromURL("/tmp/file.txt").getLines().toList
} toOption
val futSize: Future[Int] =
for {
result <- readAsync()
list <- result
} yield list.size
val futSizeMap: Future[Option[Int]] =
readAsync().map { result: Option[List[String]] =>
result.map((list: List[String]) => list.size)
}
Future, Option, Try, Either
19. Actors
19
Hilos livianos
Orientados a eventos
class BloodRequester extends Actor {
implicit val executor = context.dispatcher
override def receive: Receive = {
case BloodRequest(request) =>
DonorDAO.findNear(request).map { donors =>
donors.foreach { donor =>
facebookNotifier ! FacebookNotify(donor, request)
}
}
}
}
Se reinician en caso de fallas
Supervisión
20. ScalaTest
20
Test Unit
trait NeoTest
extends FunSpec
with MustMatchers
with BeforeAndAfterAll
with BeforeAndAfterEach {
override def beforeEach(): Unit = {
NeoDBCleaner.cleanDB()
}
describe("UserDAOs") {
it("creates an user an checks the default group") {
withUser { (user, saved) =>
saved must be(true)
val query = s"""match (a:user {id: "${user.id.getOrElse("")}"})-[c:has_group]->(b:group) return a, b, c"""
val result = Await.result(NeoQuery.executeQuery[UserLogin, Group, HasGroupLogin](query), 2 seconds)
result.length must be(1)
}
}
}
}
Multiples Pardigmas
TDD
BDD
21. Scala wants U ;)
21
https://www.coursera.org/course/progfun
http://scala-exercises.47deg.com/koans