代码之家  ›  专栏  ›  技术社区  ›  jamborta

从泛型生成无形状记录

  •  1
  • jamborta  · 技术社区  · 7 年前

    我有这个标准 Shapeless

    case class KeyValue(key: String, value: Int)
    val kv = KeyValue("key", 1)
    
    def processCaseClass(p: KeyValue) = {
         val gen = LabelledGeneric[KeyValue] 
         gen.to(p)
    }
    

    但是,我不想使用case类的名称,而是想使用泛型,然而,以这种方式重写它是行不通的:

    def processCaseClass[KV <: Product, L <: HList](p: KV) = {
         val gen = LabelledGeneric.Aux[KV, L] 
         gen.to(p)
    }
    

    如果我改变 gen 对于隐式参数,它工作正常。

    1 回复  |  直到 7 年前
        1
  •  2
  •   HTNW    7 年前

    在中使方法泛型 T 让人摸不着头脑 是如果 processCaseClass 不知道是什么 KV ,它没有机会对其结构进行足够的分析,以做出 LabelledGeneric[KV] ,产生隐式分辨率错误。通过使其成为隐式参数,您可以转移生成 LabelledGeneric PK

    你的第一个定义是

    def processCaseClass[KV <: Product, L <: HList](p: KV): Any // Signature of pCC
    // Function body doesn't affect sig., aside from return type, so what you write is what you get
    // A sig. is the only interface between a method and the world. This method doesn't
    // say there's a relationship between KV and L in its signature, so there doesn't
    // need to be one.
    
    // Instantiate KV = (Int, Int), L = String :: String :: HNil, p = (5, 5)
    val x = processCaseClass[(Int, Int), String :: String :: HNil]((5, 5))
    // Perfectly valid to the compiler... but what is this supposed to do?