Scala as Java++

Cristian Spinetta

cristian.spinetta@despegar.com

Short intro

Agenda

  • Restricciones de Java
  • Qué es Scala?
  • Sintaxis y ejemplos
  • Inmutabilidad en Scala

Tristezas Restricciones de Java

  • "Evolución lenta"
  • No es OO de verdad
  • Verbose y MUY repetitivo
  • Falta de features modernos
  • Tipado a "medias"

Qué es Scala?

  • Java++
  • Funcional + OO
  • Corre sobre la JVM
  • Tipado estático + inferencia de tipos
  • Conciso/expresivo
  • REPL

Sintaxis: De Java a Scala

Sintaxis

Ejemplo en SCALA

Operaciones elementales

val radius: Double = 2.3;

var color: String = "red";

def area(radius: Double): Double = {
  val pi: Double = 3.141592;
  val sqRad: Double = radius * radius;
  return pi * sqRad;
}

val description: String =
  "Area is: " + area(radius);

'return' implícito

val radius: Double = 2.3;

var color: String = "red";

def area(radius: Double): Double = {
  val pi: Double = 3.141592;
  val sqRad: Double = radius * radius;
  pi * sqRad;
}

val description: String =
  "Area is: " + area(radius);

Ejemplo en SCALA

Operaciones elementales

Sintaxis

val radius: Double = 2.3;

var color: String = "red";

def area(radius: Double): Double = {
  val pi: Double = 3.141592;
  val sqRad: Double = radius * radius;
  return pi * sqRad;
}

val description: String =
  "Area is: " + area(radius);

inferencia de tipos

val radius = 2.3;

var color = "red";

def area(radius: Double) = {
  val pi = 3.141592;
  val sqRad = radius * radius;
  pi * sqRad;
}

val description = "Area is: " + area(radius);

Ejemplo en SCALA

Operaciones elementales

Sintaxis

val radius: Double = 2.3;

var color: String = "red";

def area(radius: Double): Double = {
  val pi: Double = 3.141592;
  val sqRad: Double = radius * radius;
  pi * sqRad;
}

val description: String =
  "Area is: " + area(radius);
val radius = 2.3;

var color = "red";

def area(radius: Double) = {
  val pi = 3.141592;
  val sqRad = radius * radius;
  pi * sqRad;
}

val description = "Area is: " + area(radius);

; opcional

val radius = 2.3

var color = "red"

def area(radius: Double) = {
  val pi = 3.141592
  val sqRad = radius * radius
  pi * sqRad
}

val description = "Area is: " + area(radius)

Ejemplo en SCALA

Operaciones elementales

Sintaxis

val radius = 2.3

var color = "red"

def area(radius: Double) = {
  val pi = 3.141592
  val sqRad = radius * radius
  pi * sqRad
}

val description = "Area is: " + area(radius)

{ } opcional

val radius = 2.3

var color = "red"

def area(radius: Double) = 3.141592 * radius * radius

val description = "Area is: " + area(radius)

Ejemplo en SCALA

Operaciones elementales

Sintaxis

val radius = 2.3

var color = "red"

def area(radius: Double) = 3.141592 * radius * radius

val description = "Area is: " + area(radius)

String interpolation

val radius = 2.3

var color = "red"

def area(radius: Double) = 3.141592 * radius * radius

val description = s"Area is: ${area(radius)}"

Ejemplo en SCALA

Operaciones elementales

Sintaxis

public class User {

    private Integer id;
    private String name;
    private LocalDate birthday;

    public User(Integer id, String name,
        LocalDate birthday) {
        this.id = id;
        this.name = name;
        this.birthday = birthday;
    }

    public Integer getId() { return id; }
    public void setId(Integer id){ this.id = id;}
   // Getter and Setter for rest of fields...

    @Override
    public boolean equals(Object o) {
        // usually a lot of code...
    }

    @Override
    public int hashCode() {
        // more code!
    }
}
case class User(id: Int,
                name: String,
                birthday: LocalDate)

JAVA

SCALA

DTO

  • Constructor
  • Getters (y Setters si hay var)
  • copy()
  • toString()
  • equals() y hashCode()

Sintaxis

def sort(xs:  Array[Int])  {
  def swap(i: Int,  j: Int){
    val t = xs(i); xs(i) = xs(j); xs(j) = t
  }
  def sort1(l: Int, r: Int)  {
    val pivot = xs((l + r) / 2)
    var i = l; var j = r
    while(i <= j) {
      while(xs(i) < pivot) i += 1
      while(xs(j) > pivot) j -= 1
      if (i <= j) {
        swap(i, j)
        i += 1
        j -= 1
      }
    }
    if(l < j) sort1(l, j)
    if(j  <  r) sort1(i, r)}
  sort1(0, xs.length - 1)
}
def sort(xs: Array[Int]): Array[Int] = {
  if (xs.length <= 1) xs
  else {
    val pivot = xs(xs.length / 2)
    Array.concat(
      sort(xs  filter  (pivot  >)),
           xs  filter  (pivot  ==),
      sort(xs  filter  (pivot  <)))
  }
}

Imperativo

Funcional

Versátil y expresivo

Sintaxis

Ejemplo: Quick Sort

Todas las operaciones están implementadas en la librería standard de Scala.

No hay soporte especial del compilador.

Scala permite programar de forma imperativa/objetosa o bien con un estilo funcional.

Inmutabilidad

en Scala

Los valores asignados no cambian

Inmutabilidad

A balanced attitude for Scala programmers

“Prefer vals, immutable objects, and methods without side effects. Reach for them first. Use vars, mutable objects, and methods with side effects when you have a specific need and justification for them.”

scala> val name = "Peter"
name: String = Peter

scala> name = "Paul"
<console>:8: error: reassignment to val
       name = "Paul"
            ^

Variable inmutable

scala> val names = List("Peter", "Paul")
names: List[String] = List(Peter, Paul)

scala> names :+ "Moley"
res0: List[String] = List(Peter, Paul, Moley)

Lista inmutable

Ejemplo: Cuenta bancaria

Inmutabilidad

class BankAccount {
  var balance = 0

  def deposit(amount: Int) {
    if (amount > 0) balance += amount
    else balance
  }

  def withdraw(amount: Int): Int =
    if (amount >= 0 && amount <= balance) {
      balance -= amount
      balance
    } else {
      println("insufficient funds")
      balance
    }
}

Con mutabilidad

val account = new BankAccount
account.deposit(30) // return 30
account.deposit(20) // return 20
account.withdraw(10) // return 10

// Current balance: 40
case class BankAccount(balance: Int) {

  def deposit(amount: Int) =
    if (amount > 0)
      BankAccount(balance = balance + amount)
    else
      this

  def withdraw(amount: Int) =
    if (amount >= 0 && amount <= balance) {
      BankAccount(balance = balance - amount)
    } else {
      println("insufficient funds")
      this
    }
}

Con inmutabilidad

BankAccount(0)
  .deposit(30) // return a new BankAccount
  .deposit(20) // return a new one
  .withdraw(10) // return a new one

// Balance in the last BankAccount: 40

Inmutabilidad: No se cambia el valor, se crea uno nuevo.

Instalar Scala + SBT + Intellij IDEA:

https://www.scala-lang.org/download/

¡ Workshop !

Scala as Java++

By Cristian Spinetta

Scala as Java++

Short intro for Workshop Scala as Java++

  • 350