Scala中的映射类型 [英] Mapped types in Scala
问题描述
是否有一种方法可以从Scala中的现有类型派生类型?
Is there a way to derive a type from an existing one in Scala?
例如,对于case class Person(name: String, age: Int)
,我想获得(Option[String], Option[Int])
的Product
/Tuple
,即从现有的映射的类型.
For example, for case class Person(name: String, age: Int)
I'd like to get a Product
/Tuple
of (Option[String], Option[Int])
, i.e. a type mapped from an existing one.
Typescript中有一个功能(映射类型),该功能可以相对容易,这就是我开始思考这条道路的方式.但是我不确定如何在Scala中完成类似的事情.
There's a feature in Typescript (mapped types) that allows this relatively easily, which is how I started thinking down this path. But I'm not sure how something like this would be done in Scala.
我觉得解决方案涉及以某种方式使用无变形,但我不确定如何到达.
I feel like the solution involves using shapeless in some way but I'm not sure how to get there.
推荐答案
使用Shapeless可以定义类型类
With Shapeless you can define type class
import shapeless.ops.{hlist, product, tuple}
import shapeless.poly.~>
import shapeless.{Generic, HList, Id, the}
trait Partial[A] {
type Out
}
object Partial {
type Aux[A, Out0] = Partial[A] { type Out = Out0 }
object optionPoly extends (Id ~> Option) {
override def apply[T](t: T): Option[T] = null
}
// implicit def mkPartial[A, L <: HList, L1 <: HList](implicit
// generic: Generic.Aux[A, L],
// mapper: hlist.Mapper.Aux[optionPoly.type, L, L1],
// tupler: hlist.Tupler[L1]): Aux[A, tupler.Out] = null
implicit def mkPartial[A, T](implicit
toTuple: product.ToTuple.Aux[A, T],
mapper: tuple.Mapper[T, optionPoly.type],
): Aux[A, mapper.Out] = null
}
并使用它(the
是implicitly
的改进版)
and use it (the
is improved version of implicitly
)
case class Person(name: String, age: Int)
// val pp = the[Partial[Person]]
// type PersonPartial = pp.Out
type PersonPartial = the.`Partial[Person]`.Out
implicitly[PersonPartial =:= (Option[String], Option[Int])]
这篇关于Scala中的映射类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!