簡體   English   中英

我可以使用Scala抽象類型的“嵌套”來簡化類定義嗎?

[英]Can I use 'nesting' with Scala abstract types to simplify class definitions?

我正在努力了解如何盡可能地將Scala的抽象類型用作DRY / simple。 假設我有以下內容:

trait Product
trait Pallet[A <: Product]
class Import[
  A <: Product,
  B <: Pallet[A]] {

  def offload(): List[A] = {
    ...
  } 
}

class Fridge extends Product
class FridgePallet extends Pallet[Fridge]

val fridges = new Import[Fridge, FridgePallet]()

這有效,但感覺有點冗長 - 鑒於編譯器知道FridgePallet是用Fridge鍵入的,有沒有一種方法可以簡化Import類的輸入以消除顯式A <: Product聲明的需要? 我想我正在尋找類似下面的東西(這不起作用):

class Import[B <: Pallet[A <: Product]] {
  def offload(): List[A] = ...
}
val fridges = new Import[FridgePallet]()

我也試過用_ s代替A - 但是我必須使用.asInstanceOf[List[Fridge]]轉換來獲得offload()輸出的類型特異性。

我錯過了什么/不理解?

在使用泛型類型時,我沒有看到這樣做的方法,但是如果你可以使用類型成員,那么你得到:

trait Product
trait Pallet {
  type A <: Product
}
class Import[B <: Pallet] {
  def offload(): List[B#A] = { ... }
}

class Fridge extends Product
class FridgePallet extends Pallet {
  type A = Fridge
}

val fridges = new Import[FridgePallet]()
trait Pallet[A <: Product] {
  type ptype = A
}

class Import[P <: Pallet[_]] {
  def offload(): List[P#ptype] = ...
}

暫無
暫無

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

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