簡體   English   中英

Scala:“從mixin類型別名繼承時,需要類類型,{{trait} {trait}找到”

[英]Scala: “class type required but {trait} with {trait} found” when inheriting from mixin type alias

我定義了一個非常常見的類型別名:

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

這里發生了什么?

我不認為你可以像這樣直接擴展復合類型。 也就是說, 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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM