Skip to content

Instantly share code, notes, and snippets.

@srenault
Created November 14, 2013 11:02
Show Gist options
  • Save srenault/7464989 to your computer and use it in GitHub Desktop.
Save srenault/7464989 to your computer and use it in GitHub Desktop.
sealed trait Literal extends Term {
def asOpt[A <: Literal](): Option[A] = {
this match {
case x: A => Some(x)
case _ => None
}
}
}
@srenault
Copy link
Author

abstract type pattern A is unchecked since it is eliminated by erasure
[warn] case x: A => Some(x)

@mandubian
Copy link

trait Literal {
  def asOpt[A : LiteralCast](): Option[A] = implicitly[LiteralCast[A]].asOpt(this)
}
case class LiteralString(str: String) extends Literal
trait LiteralCast[A] {
  def asOpt(lit: Literal): Option[A]
}

implicit object LiteralStringCast extends LiteralCast[LiteralString] {
  def asOpt(lit: Literal): Option[LiteralString] = lit match {
    case l:LiteralString => Some(l)
    case _ => None
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment