我在ScalaFX项目工作 . 在这一刻,我正在调整 javafx.scene.control.cell
中的类 . 在此包中,具有相同签名的方法在许多类中重复 . 例如StringConverter<T> converter() . 为了避免不必要的代码重复(以及知道如何使用存在类型),我创建了以下代码:
// 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.util.StringConverter [T]的javafx.beans.property.ObjectProperty .
在 ConvertableCell
trait中,我的意图是委托值(来自 SFXDelegate
trait)必须是 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的类型参数bounds [C <:scalafx.scene.control.cell.package.JfxConvertableCell [T],T]
我明白了什么问题吗? CheckBoxListCell
有 converterProperty
方法 . 我们不能将类型和存在类型用作我们适合委托类的模具吗?
1 回答
问题在于
converterProperty
的定义 . 您将其定义为无参数方法,而scala将其视为具有空参数列表的方法 . 只是这样做可以正确编译:虽然scala将无参数方法和带有空参数列表的方法视为与覆盖相关的基本相同(参见scala spec @ 5.1.4),但它们仍然是不同的entites . 当与java代码(没有无参数方法的概念)交互时,一个nullary方法被视为具有空参数列表的方法,而不是无参数方法,因此结构类型不匹配 .