2017-10-10 154 views
1

我正在寻找一种“放松”类型别名的方法。如何在Scala中获取类型构造函数的参数?

在以下示例中,只有'O'具有在第二个type别名行中定义的类型别名。

type CodebookDetails = List[(String, List[String])] 
type O[I] = CodebookDetails 
requestDecodeIterable[I, O](request) 

是否有可能得到I以类似的方式,还是一个只需要复制和粘贴类型,像这样?:

requestDecodeIterable[(String, List[String]), List](request) 
+1

在您的例子, '''型CodebookDetails =列表[(字符串,列表[字符串])] O型[I] = CodebookDetails''' 的'I'是无意义的。也就是说,它相当于一个const函数'f(x)= 4'。 – wheaties

+1

恐怕你必须定义:type I =(String,List [String])可能会在新一代的scala中,看看你是否有时间:http://dotty.epfl.ch/docs /internals/higher-kinded-v2.html – Pavel

回答

1

你可以用无形的the宏:

// Typelevel function unapplies unary type constructors: 
// F[A] => (F, A) 
// I think I recall seeing it somewhere in shapeless, but I can't find it, 
// so I implemented it myself 
sealed trait Unapp1[T] { type F[_]; type A; implicit def eq: F[A] =:= T } 
object Unapp1 { 
    type Aux[T0, F0[_], A0] = Unapp1[T0] { type F[X] = F0[X]; type A = A0 } 
    implicit def source[F0[_], A0]: Aux[F0[A0], F0, A0] = new Unapp1[F0[A0]] { 
    type F[X] = F0[X] 
    type A = A0 
    override def eq: F[A] =:= F0[A0] = implicitly 
    } 
    def apply[T](implicit unapp: Unapp1[T]): unapp.type = unapp 
} 

// the.`tpe` looks up the implicit value of type tpe and gives it a stable path 
// suitable for type selection 
requestDecodeIterable[the.`Unapp1[CookbookDetails]`.A, the.`Unapp1[CookbookDetails]`.F](request) 

这种情况并不是真正的改善,尤其是因为我认为推理者可以自己做,但它可能有其他用途。

编辑:发现它:它的形状叫做Unpack1

相关问题