Skip to content

Instantly share code, notes, and snippets.

@matsu-chara
Last active November 20, 2015 10:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matsu-chara/702b7046eb890c4c0fe4 to your computer and use it in GitHub Desktop.
Save matsu-chara/702b7046eb890c4c0fe4 to your computer and use it in GitHub Desktop.
ネストしたjsonのような構造(必須でない要素あり)に簡単にアクセスするための ?メソッド
name := "OptionValueAccessor"
version := "1.0"
scalaVersion := "2.11.6"
libraryDependencies += "org.scala-lang" % "scala-reflect" % scalaVersion.value
package OptionValueAccessor
import scala.language.experimental.macros
import scala.reflect.macros.whitebox.Context
object OptionValueAccessor {
implicit class OptValue[A, B](val self: Option[A])(implicit ev: A <:< {def value: B}) {
def ? : Option[B] = macro Impl.optValImpl[A, B]
}
implicit class OptOpt[A, B](val self: Option[Option[A]])(implicit ev: A <:< {def value: B}) {
def ? : Option[B] = macro Impl.optOptImpl[A, B]
}
object Impl {
def optValImpl[A: c.WeakTypeTag, B: c.WeakTypeTag](c: Context): c.Expr[Option[B]] = {
import c.universe._
c.Expr[Option[B]](q"${c.prefix}.self.map {_.value}")
}
def optOptImpl[A: c.WeakTypeTag, B: c.WeakTypeTag](c: Context): c.Expr[Option[B]] = {
import c.universe._
c.Expr[Option[B]](q"${c.prefix}.self.flatten.map {_.value}")
}
}
}
package OptionValueAccessor
import OptionValueAccessor._
object OptionValueAccessorTest {
case class A(value: Int)
case class B(value: Option[A])
case class C(value: Option[B])
case class D(value: Option[C])
case class E(value: D)
def main(args: Array[String]): Unit = {
val edcba = Some(E(D(Some(C(Some(B(Some(A(1)))))))))
println(edcba.?.?.?.?.?) // Some(1)
val ednon = Some(E(D(None)))
println(ednon.?.?.?.?.?) // None
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment