我在ScalaFX項目中工作。在這一刻,我正在適應javafx.scene.control.cell
的課程。在這個包中,具有相同簽名的方法被複制到許多類中。例如StringConverter<T> converter()
。爲了避免不必要的重複代碼(並知道如何使用存在的類型),我創建了下面的代碼:類型作爲Scala的授權類的模型
// Defined in scalafx.util package. All classes in scalafx use this trait
package scalafx.util
trait SFXDelegate[+D <: Object] extends AnyRef {
def delegate: D
override def toString = "[SFX]" + delegate.toString
override def equals(ref: Any): Boolean = {
ref match {
case sfxd: SFXDelegate[_] => delegate.equals(sfxd.delegate)
case _ => delegate.equals(ref)
}
}
override def hashCode = delegate.hashCode
}
// Package Object
package scalafx.scene.control
import javafx.{ util => jfxu }
import javafx.beans.{ property => jfxbp }
import javafx.scene.{ control => jfxsc }
import scalafx.Includes._
import scalafx.beans.property.ObjectProperty
import scalafx.util.SFXDelegate
import scalafx.util.StringConverter
package object cell {
type Convertable[T] = {
def converterProperty: jfxbp.ObjectProperty[jfxu.StringConverter[T]]
}
type JfxConvertableCell[T] = jfxsc.Cell[T] with Convertable[T]
trait ConvertableCell[C <: JfxConvertableCell[T], T]
extends SFXDelegate[C] {
def converter: ObjectProperty[StringConverter[T]] = ObjectProperty(delegate.converterProperty.getValue)
def converter_=(v: StringConverter[T]) {
converter() = v
}
}
}
在JfxConvertableCell
型我想說
我喜歡的類型是
T
型javafx.scene.control.Cell
它有一個名爲converterProperty
的方法,返回javafx.beans.property.ObjectProperty
類型javafx.util.StringConverter[T]
。
雖然ConvertableCell
特質,我的意思是說,(從SFXDelegate
性狀)該委託值必須爲JfxConvertableCell
類型。我試圖創建第一類是的CheckBoxListCell
反部分:
package scalafx.scene.control.cell
import javafx.scene.control.{cell => jfxscc}
import scalafx.scene.control.ListCell
import scalafx.util.SFXDelegate
class CheckBoxListCell[T](override val delegate: jfxscc.CheckBoxListCell[T] = new jfxscc.CheckBoxListCell[T])
extends ListCell[T](delegate)
with ConvertableCell[jfxscc.CheckBoxListCell[T], T]
with SFXDelegate[jfxscc.CheckBoxListCell[T]] {
}
但是在這一刻,我從編譯器這樣的信息:
類型參數[javafx.scene.control.cell .CheckBoxListCell [T],T]不符合特質ConvertableCell的類型參數界限[C <:scalafx.scene.control.cell.package.JfxConvertableCell [T],T]
我才明白什麼了嗎? CheckBoxListCell
有converterProperty
方法。我們不能使用類型和存在類型作爲我們適合我們的委託類的模具嗎?
我不舒服爲什麼它不起作用。 你可以使用一些隱式轉換來轉換爲你想要的類型嗎? https://gist.github.com/257758 – axaluss
可能是關係CheckBoxListCell <:JfxConvertableCell不是真的,因爲編譯器不夠聰明,看不到這個。 – axaluss