2017-10-10 215 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

相關問題