[英]Scala: “class type required but {trait} with {trait} found” when inheriting from mixin type alias
I have a very common type alias defined: 我定义了一个非常常见的类型别名:
package object policy {
type KeyGen[K] = Function0[K] with Serializable
}
But when I try to inherit from it: 但是当我尝试继承它时:
import java.security.Key
case class FixedKeyGen(key: Key) extends KeyGen[Key] {
override def apply(): Key = key
}
The maven compiler gave me the following error: maven编译器给了我以下错误:
[ERROR] /home/peng/git/datapassport/core/src/main/scala/com/schedule1/datapassport/policy/ValueMapping.scala:16: class type required but () => java.security.Key with Serializable found
[ERROR] case class FixedKeyGen(key: Key) extends KeyGen[Key] {
[ERROR] ^
[ERROR] /home/peng/git/datapassport/core/src/main/scala/com/schedule1/datapassport/policy/ValueMapping.scala:16: com.schedule1.datapassport.policy.KeyGen[java.security.Key] does not have a constructor
[ERROR] case class FixedKeyGen(key: Key) extends KeyGen[Key] {
What is going on here? 这里发生了什么?
I don't think you're allowed to extend a compound type directly like that. 我不认为你可以像这样直接扩展复合类型。 That is,
Function0[K] with Serializable
isn't a class type in and of itself. 也就是说,
Function0[K] with Serializable
本身不是类类型。 It is a compound type without a constructor, and that's the key. 它是没有构造函数的复合类型,这是关键。 It doesn't really make sense to extend something without a constructor.
在没有构造函数的情况下扩展某些东西并没有多大意义。 The type alias does something similar to this (note the parentheses around the type):
类型别名执行与此类似的操作(请注意类型周围的括号):
case class FixedKeyGen(key: Key) extends (Function0[Key] with Serializable) {
override def apply(): Key = key
}
We get the same error: 我们得到了同样的错误:
<console>:20: error: class type required but () => java.security.Key with Serializable found
case class FixedKeyGen(key: Key) extends (Function0[Key] with Serializable) {
This is because Function0[Key] with Serializable
isn't a class type. 这是因为
Function0[Key] with Serializable
不是类类型。
But, this of course works if I remove the parentheses. 但是,如果我删除括号,这当然有效。 Without them,
FixedKeyGen
is extending Function0
and mixing Serializable
. 没有它们,
FixedKeyGen
正在扩展Function0
并混合Serializable
。 With them, it's trying to extend a compound type. 有了它们,它正试图扩展复合类型。
To work around this, you may want to just use a trait, instead: 要解决此问题,您可能只想使用特征,而不是:
trait KeyGen[K] extends Function0[K] with Serializable
case class FixedKeyGen(key: Key) extends KeyGen[Key] {
override def apply(): Key = key
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.