Last active
November 20, 2015 10:00
-
-
Save matsu-chara/702b7046eb890c4c0fe4 to your computer and use it in GitHub Desktop.
ネストしたjsonのような構造(必須でない要素あり)に簡単にアクセスするための ?メソッド
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name := "OptionValueAccessor" | |
version := "1.0" | |
scalaVersion := "2.11.6" | |
libraryDependencies += "org.scala-lang" % "scala-reflect" % scalaVersion.value |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}") | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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