【问题标题】:Generate Shapeless Record from Generics从泛型生成无形记录
【发布时间】:2017-09-15 23:38:21
【问题描述】:

我有这个标准Shapeless代码:

case class KeyValue(key: String, value: Int)
val kv = KeyValue("key", 1)

def processCaseClass(p: KeyValue) = {
     val gen = LabelledGeneric[KeyValue] 
     gen.to(p)
}

但是我不想使用案例类的名称,而是使用泛型,但是,这样重写它不起作用:

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

如果我将 gen 更改为隐式参数,它可以正常工作。

上面的代码有什么问题?

【问题讨论】:

    标签: scala generics shapeless


    【解决方案1】:

    T 中创建一个泛型方法会让人不知道T 是什么。如果processCaseClass 不知道KV 是什么,它就没有机会分析其结构以生成LabelledGeneric[KV],从而产生隐式解析错误。通过将其设为隐式参数,您将生成 LabelledGeneric 的责任转移给调用者,它实际上有可能得到满足,因为调用者会知道 PK 是什么。

    你对processCaseClass 的第一个定义做了一件奇怪的事情,这足以表明它不可能是正确的:

    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?
    

    【讨论】:

    • 感谢您的解释。现在说得通了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 2014-06-03
    • 1970-01-01
    相关资源
    最近更新 更多