0
是否有任何方式對通用類型A進行限制,使得A必須具有給定的方法?我知道,在F#它可以像這樣斯卡拉通用類型函數限制像F#
type GenericState<'A when 'A:comparison>
也就是說一個必須是具有比較功能的類型來完成。我想知道這是否可以在斯卡拉輕鬆完成
是否有任何方式對通用類型A進行限制,使得A必須具有給定的方法?我知道,在F#它可以像這樣斯卡拉通用類型函數限制像F#
type GenericState<'A when 'A:comparison>
也就是說一個必須是具有比較功能的類型來完成。我想知道這是否可以在斯卡拉輕鬆完成
有一對夫婦。
下界
trait Behaviour {
def someMethod...
}
// GenericState has to inherit from Behaviour and therefore
// implement someMethod
type GenericState <: Behaviour
語境界定
trait Behaviour[T] {
def someMethod ..
}
// T has to inherit from GenericState and have
// an implicit Behaviour[T] in scope.
class Test[T <: GenericState : Behaviour] {
// this is a good way to decouple things
// You can get a reference to the materialized bound with implicitly
// and call your method on that.
implicitly[Behaviour[T]].someMethod(..)
}
結構類型
不建議最直接等同,因爲它不具有高性能在JVM上執行。
// This creates a type definition in place and it's effectively similar
// to the first variant, except the type is structurally defined.
type GenericState <: {
def someMethod ..
}
我個人更喜歡在這裏綁定的上下文。
trait Comparable[T] {
def compare(x: T, y: T): Int
}
object Comparable {
implicit val intComparable = new Comparable[Int] {
def compare(x: Int, y: Int): Int = ..
}
// and so on
}
然後,只要您需要某種可比較的東西,就可以使用上下文邊界。
class Something[T : Comparable](obj: T)
這只是語法糖:
class Something[T](obj: T)(implicit ev: Comparable[T])