Skip to content

Instantly share code, notes, and snippets.

@Fristi
Created January 1, 2017 13:30
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 Fristi/747de1ada708ea2ae1371e2e7c26facc to your computer and use it in GitHub Desktop.
Save Fristi/747de1ada708ea2ae1371e2e7c26facc to your computer and use it in GitHub Desktop.
Accessing elements via optics in a Map[String, Any]
package maps
import monocle._
import monocle.std.map._
import monocle.function.all._
import scala.reflect.ClassTag
object Test extends App {
def get[A](key: String) = at[Map[String, Any], String, Option[Any]](key)
def as[A](implicit CT: ClassTag[A]) =
Optional[Option[Any], A] {
case Some(x : A) => Some(x)
} { x => _ => Some(x) }
private val name = get("name") ^|-? as[String]
private val age = get("age") ^|-? as[Int]
val f1 = name.set("Mark")
val f2 = age.set(2)
println(as[Int].set(2).apply(None))
val composed = f1 andThen f2
val map = composed(Map.empty)
println(map)
println(name.getOption(map))
println(age.getOption(map))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment