【问题标题】:Scala: "class type required but {trait} with {trait} found" when inheriting from mixin type aliasScala:从mixin类型别名继承时“需要类类型,但找到带有{trait}的{trait}”
【发布时间】:2015-05-18 21:33:31
【问题描述】:

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

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

这是怎么回事?

【问题讨论】:

    标签: scala inheritance mixins


    【解决方案1】:

    我不认为你可以像这样直接扩展复合类型。也就是说,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,而不是:

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

    【讨论】:

    • 非常感谢!这听起来对我来说是一个缺失的功能
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    相关资源
    最近更新 更多