カジュアルかつ型安全に Scalaオブジェクト <--> JSON文字列 の変換したい。
JSON化:
scala> import jp.t2v.util.json._
import jp.t2v.util.json._
scala> List(10, 20, 30).toJson
import play.db.anorm._ | |
import play.db.anorm.defaults._ | |
trait Identifiable[A] { | |
type ID = A | |
val id: Pk[ID] | |
} | |
trait ExMagic[A <: Identifiable[_]] extends Magic[A] { | |
final Map<String, Object> attributes = new HashMap<String, Object>(); | |
final Enumeration<String> names = (Enumeration<String>) session.getAttributeNames(); // SuppressWarnings! | |
for (;names.hasMoreElements();) { | |
final String key = names.nextElement(); | |
final Object value = session.getAttribute(key); | |
attributes.put(key, value); | |
} | |
session.invalidate(); | |
final HttpSession newSession = httpServletRequest.getSession(true); | |
for (final Entry<String, Object> entry : attributes.entrySet()) { |
package com.hirarie.scala.test | |
import java.awt.Point | |
class RichPoint(private val p: Point) { | |
def +(other: Point) = new Point(p.x + other.x, p.y + other.y) | |
} | |
object RichPoint { | |
implicit def pointToRichPoint(p: Point) = new RichPoint(p) |
trait Secure { | |
self: Controller => | |
@Before | |
def check = parseAuthHeader match { | |
case None => Unauthorized("Basic") | |
case Some(user) => | |
renderArgs += "user" -> user | |
Continue | |
} |
implicit def toGrepCallable[A](list: Traversable[A]) = new { | |
def grep[B](regex: String)(func: A => B = identity _)(implicit v: A =:= String) = | |
list.collect { | |
case s if regex.r.findFirstIn(s).isDefined => func(s) | |
} | |
} |
object PimpGrepToCollection { | |
implicit def toGrepCallable(list: Traversable[String]) = new { | |
def grep[A](regex: String)(func: String => A = identity _) = | |
list.collect { | |
case s if regex.r.findFirstIn(s).isDefined => func(s) | |
} | |
} | |
def main(args: Array[String]) { |
object Json { | |
trait ToJson[-A] { | |
def apply(value: A): String | |
} | |
def toJson[A](value: A)(implicit t: ToJson[A]): String = t(value) | |
implicit def traversableToJson[A](implicit t: ToJson[A]) = new ToJson[Traversable[A]] { | |
def apply(value: Traversable[A]): String = value.map(n => toJson(n)).mkString("[", ", ", "]") |
import scala.annotation._ | |
object Factorization { | |
/** 素数 */ | |
type Prime = Long | |
/** 指数 */ | |
type Exponent = Int | |
val primes: Stream[Prime] = 2 #:: sieve(3) |
trait TupleOr { | |
implicit def tuple1Or[A](t: (A, )) = new { | |
def ++[B](o: (B, )) = (t._1, o._1) | |
def ++[B, C](o: (B, C)) = (t._1, o._1, o._2) | |
def ++[B, C, D](o: (B, C, D)) = (t._1, o._1, o._2, o._3) | |
def ++[B, C, D, E](o: (B, C, D, E)) = (t._1, o._1, o._2, o._3, o._4) | |
def ++[B, C, D, E, F](o: (B, C, D, E, F)) = (t._1, o._1, o._2, o._3, o._4, o._5) | |
// ... | |
} |