F#

2017-06-15 7 views
0

のような一般的な型の関数の制限をスキャリブレーションA型に制限を設定する方法はありますか?私はF#でこのようにすることができることを知っていますF#

type GenericState<'A when 'A:comparison> 

これは、Aが比較関数を持つ型でなければならないということです。これがScalaで簡単にできるかどうか疑問に思う。

答えて

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