簡體   English   中英

具有私有構造函數和隱式參數的Scala類

[英]Scala class with a private constructor and implicit parameter

我想向帶有私有構造函數的類添加隱式參數。 作為簡化示例:

class A[T] private(a:Int){ 
  def this()=this(0)
}

如果我想使用Ordered [T]將Pimp我的庫模式應用於T,則需要使用(已棄用的)視圖綁定,如下所示:

class A[T <% Ordered[T]] private(a:Int){ 
  def this()=this(0)
}

這可行。 但是,為了避免使用過時的語法糖,我想將隱式參數傳遞給該類。 不幸的是,這可能是我做錯事的地方:

class A[T] private(a:Int)(implicit conv:T=>Ordered[T]){ 
  def this()=this(0)
}

對於以上代碼,編譯器將生成以下錯誤:

error: No implicit view available from T => Ordered[T].
       def this()=this(0)

而如果我嘗試像這樣直接傳遞隱式參數:

class A[T] private(a:Int)(implicit conv:T=>Ordered[T]){ 
  def this()=this(0)(conv)
}

我得到這個:

error: not found: value conv
       def this()=this(0)(conv)

在這種情況下,如何傳遞隱式參數?

編輯:經過更多的實驗后,似乎用隱式參數重新定義構造函數是問題。 並非構造函數是私有的。

我找到了答案,看來我需要為無參數構造函數顯式定義隱式參數,例如:

class A[T] private(a:Int)(implicit conv:T=>Ordered[T]){ 
  def this()(implicit conv:T=>Ordered[T])=this(0)
}

對於垃圾郵件,我深表歉意,無論如何,我將接受任何提供更深入說明的答案。

Scala提供兩種排序方式,一種是通過繼承Ordered ,而另一種實際上更合適,這是通過使用Ordering類型類的上下文邊界。

您的方法實際上並不是慣用的,如果您有一些東西實際使用了您提供的隱式,則在編譯時會得到一個模棱兩可的隱式異常,因為構造函數和方法都定義了相同的隱式。

我要做的是:

class A[T : Ordering] private(a: Int)

這實際上是以下內容的簡寫語法:

class A[T] private(a: Int)(implicit ev: Ordering[T])

然后,您可以顯式或implicitly使用此參數。 如果使用速記T : Ordering定義它T : Ordering語法。

class A[T : Ordering] private(a: Int) {
  def revSorter(list: List[T]): List[T] = {
    list.sorted(implicitly[Ordering[T]].reverse)
  }
}

如果使用“顯式”語法定義它:

class A[T] private(a: Int)(implicit ev: Ordering[T]) {
      def revSorter(list: List[T]): List[T] = {
        list.sorted(ev.reverse)
      }
    }

暫無
暫無

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

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