作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
使用 Shapeless,我尝试通过以下方式获取 Generic[F]
:
import shapeless._
class F(x: Int)
但是失败了:
scala> Generic[F]
<console>:20: error: could not find implicit value for parameter gen: shapeless.Generic[F]
Generic[F]
^
shapeless 可以生成 Generic[F]
吗?如果是,怎么办?
最佳答案
您希望F
的表示形式是什么?你可以说它应该是 HNil
,但是 x
在类的主体之外是不可见的,所以 Shapeless 决定根本不提供任何实例.这“只是”一个设计决定——在我看来是正确的,但很容易想象 Shapeless 为您的类提供 HNil
实例。
为 F
定义您自己的实例也相当容易,这是可能的,因为 Generic
只是另一个类型类:
import shapeless._
class F(x: Int)
object F {
implicit val genericF: Generic.Aux[F, HNil] = new Generic[F] {
type Repr = HNil
def from(r: HNil): F = new F(0)
def to(t: F): HNil = HNil
}
}
作为另一个答案说明,您可以通过将您的类更改为案例类来让 Shapeless 为您提供一个实例。不过,这不是唯一的方法——您还可以将构造函数参数更改为 val
或直接将其删除:
scala> class F(val x: Int)
defined class F
scala> shapeless.Generic[F]
res0: shapeless.Generic[F]{type Repr = shapeless.::[Int,shapeless.HNil]} = anon$macro$3$1@73e5dfa9
scala> class F()
defined class F
scala> shapeless.Generic[F]
res1: shapeless.Generic[F]{type Repr = shapeless.HNil} = anon$macro$5$1@4e0e355c
不过,您不能将参数设为 var
或将类设为抽象类(除非它是密封的并且具有案例类或对象实现)。或者更确切地说,您可以,但是您必须再次定义自己的实例,并且您将违反 Generic
文档中的约定,该文档指出特征类型应该是“不可变数据”具有构造和解构实例的规范方式的类型”。
据我所知,关于什么样的类定义安排将获得 Generic
实例的确切细节没有在任何地方记录(并且 the source 不容易阅读),但它很漂亮通过在 REPL 中尝试特定案例,轻松测试您感兴趣的限制。
关于scala - Generic[A] 其中 A 是一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41477065/
我是一名优秀的程序员,十分优秀!