tri*_*oid 2 inheritance scala mixins
我定义了一个非常常见的类型别名:
package object policy {
type KeyGen[K] = Function0[K] with Serializable
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试继承它时:
import java.security.Key
case class FixedKeyGen(key: Key) extends KeyGen[Key] {
override def apply(): Key = key
}
Run Code Online (Sandbox Code Playgroud)
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] {
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?
我不认为你可以像这样直接扩展复合类型.也就是说,Function0[K] with Serializable它本身不是类类型.它是没有构造函数的复合类型,这是关键.在没有构造函数的情况下扩展某些东西并没有多大意义.类型别名执行与此类似的操作(请注意类型周围的括号):
case class FixedKeyGen(key: Key) extends (Function0[Key] with Serializable) {
override def apply(): Key = key
}
Run Code Online (Sandbox Code Playgroud)
我们得到了同样的错误:
<console>:20: error: class type required but () => java.security.Key with Serializable found
case class FixedKeyGen(key: Key) extends (Function0[Key] with Serializable) {
Run Code Online (Sandbox Code Playgroud)
这是因为Function0[Key] with Serializable不是类类型.
但是,如果我删除括号,这当然有效.没有它们,FixedKeyGen正在扩展Function0和混合Serializable.有了它们,它正试图扩展复合类型.
要解决此问题,您可能只想使用特征,而不是:
trait KeyGen[K] extends Function0[K] with Serializable
case class FixedKeyGen(key: Key) extends KeyGen[Key] {
override def apply(): Key = key
}
Run Code Online (Sandbox Code Playgroud)