Skip to content

Instantly share code, notes, and snippets.

View rdecaire's full-sized avatar

Robert DeCaire rdecaire

  • Inflection Group
  • Toronto
View GitHub Profile
val lRight = r.left
// lRight: scala.util.Either.LeftProjection[String,User] =
// LeftProjection(Right(User(Sam,24)))
lRight.map(_.toUpperCase)
// scala.util.Either[String,User] = Right(User(Sam,24))
val lProjection = l.left
// lProjection: scala.util.Either.LeftProjection[String,User] =
// LeftProjection(Left(I'm an error!))
lProjection.map(_.toUpperCase)
// scala.util.Either[String,User] = Left(NOT A USER)
def lefty(s: String): String = "This was an error: " + s
// lefty: (s: String)String
def righty(u: User): String = "This was a user: " + u.name
// righty: (u: User)String
r.fold(lefty, righty)
// String = This was a user: Sam
l.fold(lefty, righty)
// String = This was an error: Not a user
r match {
case Right(a) => println("User is named " + a.name)
case Left(b) => println("Error! " + b)
}
// User is named Sam
val f: Either[String, User] = Left("I'm an error!")
// f: Either[String,User] = Left(I'm an error!)
f.map(either)
// scala.util.Either[String,Either[String,Int]] = Left(I'm an error!)
f.flatMap(either)
// scala.util.Either[String,Int] = Left(I'm an error!)
def either(u: User): Either[String, Int] = {
  if(u.name.size == 0) Left("No name!")
  else Right(u.name.size)
}
// either: (u: User)Either[String,Int]
r.map(either)
// scala.util.Either[String,Either[String,Int]] = Right(Right(3))
r.flatMap(either)
// scala.util.Either[String,Int] = Right(3)
r.map(user => user.name.toUpperCase)
// scala.util.Either[String,String] = Right(SAM)
val x = Left("Not a user")
//x: scala.util.Left[String,Nothing] = Left(Not a user)
val x = Right(u)
// x: scala.util.Right[Nothing,User] = Right(User(Sam,24))
case class User(name: String, age: Int)
// defined class User
val u = User("Sam", 24)
// u: User = User(Sam,24)
val r: Either[String, User] = Right(u)
// r: Either[String,User] = Right(User(Sam,24))
val l: Either[String, User] = Left("Not a user")
// l: Either[String,User] = Left(Not a user)