android.os.Bundle
この方法でバンドルを生成することを目指して、APIを抽象化しようとしています。
case class MyClass( a: Int, b: String )
val mc = MyClass( 3, "5" )
implicit val bundleable = Bundle.from[MyClass]()
val bundle = bundleable.write( mc )
assert( mc == bundleable.read( bundle ) )
ケース クラスを に変換しLabelledGeneric
、キーと値のペアを に書き込むのBundle
は簡単です。Bundle
しかし、値を元の型に戻す方法が見つかりません。そこにある多数のJSONライブラリがすでにこの問題を解決していると思いますが、続行する方法の手がかりを見つけることができません。
object Bundle {
def from[T] = new {
def apply[LG <: HList, K <: HList, N <: Nat]()(
implicit
lg: LabelledGeneric.Aux[T, LG],
l: Length.Aux[LG, N],
k: Keys.Aux[LG, K],
lfw: LeftFolder.Aux[LG, Bundle, fold.write.type, Bundle],
//lfr: LeftFolder.Aux[K, Bundle, fold.read.type, LG],
ti: ToInt[N]
) = new Bundleable[T] {
override def write( value: T ): Bundle = {
lg.to( value ).foldLeft( new Bundle( toInt[N] ) )( fold.write )
}
override def read( bundle: Bundle ): T = ???
}
}
object fold {
object write extends Poly2 {
implicit def default[K <: Symbol, V: Bundleize]( implicit key: Witness.Aux[K] ): Case.Aux[Bundle, FieldType[K, V], Bundle] = {
at { ( bundle, value ) ⇒
implicitly[Bundleize[V]].write( key.value.name, value, bundle )
bundle
}
}
}
object read extends Poly2 {
???
}
}
}
/**
* Read or write a single value from/into a Bundle
*/
trait Bundleize[T] {
def read( key: String, bundle: Bundle ): T
def write( key: String, value: T, bundle: Bundle ): Unit
}
/**
* Transformation T <> Bundle
*/
trait Bundleable[T] {
def read( bundle: Bundle ): T
def write( value: T ): Bundle
}
また、 (括弧を省略して)Bundle.from[MyClass]
ではなく、私が書くことができるような方法でコードを再構築する方法はありますか?Bundle.from[MyClass]()