Scala:“从mixin类型别名继承时,需要类类型,{{trait} {trait}找到”

时间:2015-03-16 16:48:05

标签: scala inheritance mixins

我定义了一个非常常见的类型别名:

package object policy {

  type KeyGen[K] = Function0[K] with Serializable
}

但是当我尝试继承它时:

import java.security.Key
case class FixedKeyGen(key: Key) extends KeyGen[Key] {

  override def apply(): Key = key
}

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] {

这里发生了什么?

1 个答案:

答案 0 :(得分:8)

我不认为您可以像这样直接扩展复合类型。也就是说,Function0[K] with Serializable本身并不属于类类型。它是一种没有构造函数的复合类型,这是关键。在没有构造函数的情况下扩展某些东西真的没有意义。类型别名与此类似(请注意类型周围的括号):

case class FixedKeyGen(key: Key) extends (Function0[Key] with Serializable) {
    override def apply(): Key = key
}

我们得到同样的错误:

<console>:20: error: class type required but () => java.security.Key with Serializable found
       case class FixedKeyGen(key: Key) extends (Function0[Key] with Serializable) {

这是因为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
}