錯誤/成功的不同資料型別

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")
    }
}

兩個值上的模式匹配

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

將任一值轉換為選項

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