簡體   English   中英

Scala通用類型函數限制,例如F#

[英]Scala generic type function restriction like F#

是否有某種方式可以限制通用類型A,使得A必須具有給定的方法? 我知道在F#中可以這樣做

type GenericState<'A when 'A:comparison>

意味着A必須是具有比較功能的類型。 我想知道這是否可以在Scala中輕松完成

有一對

下界

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM