2017-06-15 70 views
0

是否有任何方式对通用类型A进行限制,使得A必须具有给定的方法?我知道,在F#它可以像这样斯卡拉通用类型函数限制像F#

type GenericState<'A when 'A:comparison> 

也就是说一个必须是具有比较功能的类型来完成。我想知道这是否可以在斯卡拉轻松完成

回答

2

有一对夫妇。

下界

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])