Skip to content

Instantly share code, notes, and snippets.

@michaelahlers
Last active January 26, 2022 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelahlers/032cf6ec363f2ff043a8fe09f1e28722 to your computer and use it in GitHub Desktop.
Save michaelahlers/032cf6ec363f2ff043a8fe09f1e28722 to your computer and use it in GitHub Desktop.
trait JavaApi {
def isAuthenticated: Boolean
}
sealed trait IsAuthenticated
object IsAuthenticated {
def unapply(x: JavaApi): Option[IsAuthenticated] =
if (x.isAuthenticated) Some(Yes)
else Some(No)
}
case object Yes extends IsAuthenticated {
def unapply(x: JavaApi): Option[Yes.type] =
if (x.isAuthenticated) Some(Yes)
else None
}
case object No extends IsAuthenticated {
def unapply(x: JavaApi): Option[No.type] =
if (x.isAuthenticated) None
else Some(No)
}
def x: JavaApi =
new JavaApi {
override def isAuthenticated = true
}
def y: JavaApi =
new JavaApi {
override def isAuthenticated = false
}
// YES!
x match {
case IsAuthenticated(Yes) => println("YES!")
case IsAuthenticated(No) => println("No. ):")
}
// YES!
x match {
case Yes(_) => println("YES!")
case No(_) => println("No. ):")
}
// No. ):
y match {
case IsAuthenticated(Yes) => println("YES!")
case IsAuthenticated(No) => println("No. ):")
}
// No. ):
y match {
case Yes(_) => println("YES!")
case No(_) => println("No. ):")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment