错误/成功的不同数据类型
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