Scala Language O


Esempio

Diversi tipi di dati per errore / successo

def getPersonFromWebService(url: String): Either[String, Person] = {
    
    val response = webServiceClient.get(url)

    response.webService.status match {
        case 200 => {
            val person = parsePerson(response)
            if(!isValid(person)) Left("Validation failed")
            else Right(person)
        }

        case _ => Left(s"Request failed with error code $response.status")
    }
}

Pattern matching su entrambi i valori

getPersonFromWebService("http://some-webservice.com/person") match {
    case Left(errorMessage) => println(errorMessage)
    case Right(person) => println(person.surname)
}

Converti un valore in Opzione

val maybePerson: Option[Person] = getPersonFromWebService("http://some-webservice.com/person").right.toOption