scala - 如何用trait来描述算子?

标签 scala types traits

我正在尝试定义一个特征来描述基于其他运算符的运算符。像这样的事情:

trait LessThanComparable[T] {
    def < (that: T) : Boolean

    def > (that: T) = that < this
}

然后我使用它:

class Example(val x : Int) extends LessThanComparable[Example] {
    def < (that: Example) = x < that.x
}

但是我得到了这个:值<不是类型参数T的成员

我怎么能说那个和这个是同一类型呢?或者我正在尝试一些不可能的事情?

最佳答案

我想这就是你想要的:

trait LessThanComparable[T <: LessThanComparable[T]] { this: T =>
  def <(that: T): Boolean

  def >(that: T) = that < this
}

class Example(val x: Int) extends LessThanComparable[Example] {
  def <(that: Example) = x < that.x
}

为了能够说that < this ,有两件事必须成立。

  1. that必须有 <接受 T 的方法,或者换句话说,that必须是LessThanComparable[T] 。我们可以通过说 T 来确保这一点必须是 LessThanComparable[T] 的子类,或 T <: LessThanComparable[T] .

  2. this必须是T 。我们可以通过使用 self 类型 this: T => 来确保这一点.

那么,

val a = new Example(5)
val b = new Example(4)

println(a < b)  // false
println(a > b)  // true
println(b < a)  // true
println(b > a)  // false

关于scala - 如何用trait来描述算子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12539855/

相关文章:

scala - 使用scala计算字符串中相邻的重复字符

sql-server-2005 - Sql Server 2005 中的时间数据类型

rust - "the method cannot be invoked on a trait object"在单独的特征实现上

java - 在 Scala 中通过 SimpleDateFormat 转换后如何保持 DateTime 为 DateTime 格式?

json - 如何使用 json 模式验证器验证可为空类型?

scala - 强制类型差异

javascript - Highcharts JS : Gap between X-Axis labels is too thin

c++ - 确保 C++ double 为 64 位

generics - 如果我已经将特征边界添加到另一个 impl block ,为什么还需要在 impl block 上添加特征边界?

php - 如何限制某些类的 PHP 特性