scala – 具有标记类型的解码案例类

前端之家收集整理的这篇文章主要介绍了scala – 具有标记类型的解码案例类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
鉴于:

鉴于以下关于亚扪人:

@ import $ivy.`io.circe::circe-core:0.9.0` 

@ import $ivy.`io.circe::circe-generic:0.9.0`                   

@ import $ivy.`com.chuusai::shapeless:2.3.3` 

@ import shapeless.tag 
import shapeless.tag

@ trait Foo 
defined trait Foo

@ import io.circe._,io.circe.generic.semiauto._ 
import io.circe._,io.circe.generic.semiauto._

@ import shapeless.tag.@@ 
import shapeless.tag.@@

@ implicit def taggedTypeDecoder[A,B](implicit ev: Decoder[A]): Decoder[A @@ B] = 
    ev.map(tag[B][A](_)) 
defined function taggedTypeDecoder

鉴于Foo:

@ case class F(x: String @@ Foo)  
defined class F

我可以召唤一个Decoder [String @@ Foo]:

@ Decoder[String @@ Foo] 
res17: Decoder[String @@ Foo] = io.circe.Decoder$$anon$21@16b32e49

但不是F:

@ deriveDecoder[F] 
cmd18.sc:1: could not find Lazy implicit value of type io.circe.generic.decoding.DerivedDecoder[ammonite.$sess.cmd16.F]
val res18 = deriveDecoder[F]
                         ^
Compilation Failed

如何获得解码器[F]?

解决方法

这是一个无形的’懒惰 – milessabin/shapeless#309错误

我有一个PR使您的示例编译 – milessabin/shapeless#797(我使用publishLocal检查)

基本上,Lazy中的问题是它过于急切地扩展类型别名(A @@ B是带有Tagged [B]的A的类型别名),这反过来又触发了Scala错误scala/bug#10506

Scala bug看不到明确的解决方案.它是子类型与参数多态性问题的另一个化身,使类型推断变得复杂.它的要点是Scala必须同时执行子类型检查和类型推断.但是当我们将一些类型变量(如A和B)放在像A和Tagged [B]这样的精炼类型中时(实际上最终会找到一个FieldType [K,A with Tagged [B]],其中FieldType是另一种类型别名,隐藏了一个精炼类型),必须单独检查每个组件的子类型.这意味着我们选择检查组件的顺序决定了类型变量A和B的约束方式.在某些情况下,它们会过度约束或约束不足,无法正确推断.

Apropo,无形测试显示workaround,但我认为它不适用于circe,因为它使用的是某种宏,而不是使用vanilla类型派生.

长话短说,你可以:

>等待一个无形的(请upvote #797)和随后的circe释放
>不使用标记类型= /
>尝试使用不同的编码,没有精炼或结构类型 – 也许是alexknvl/newtypes? (我没试过)

猜你在找的Scala相关文章