【问题标题】:How make operator call this inside a class如何让操作员在类中调用它
【发布时间】:2012-11-13 02:21:07
【问题描述】:

我正在编写一个小型 DSL。从其他角度来看,它可以用作自定义控制结构。

这是一个小例子

case class Reference(var value : Double) {
  def apply() = value
  def update(v : Double) = value = v
}
implicit def toReference(ref:Reference) = ref.value

trait Store {
  import scala.collection.mutable.Buffer
  val index : Buffer[Reference] = Buffer()
  def ++ (v : Double) : Reference = {
    val r = Reference(v)
    index += r
    r
  }
  implicit def toSelf(u : Unit) = this
}

class ExampleStore extends Store {
  val a = () ++ 1.0
  val b = () ++ 2.0
  val c = () ++ 0.5
}


val store = new ExampleStore
store.c() = store.a + store.b

我想访问前面没有this 的类运算符,但除了在表达式开头至少指定() 之外找不到其他方法。我需要一个“前缀”表单

将这个例子改写如下

class ExampleStore extends Store {
  val a =++ 1.0
  val b =++ 2.0
  val c =++ 0.5
}

有人能想出一些技巧让 scala 接受这样的约定吗?

【问题讨论】:

    标签: scala operators dsl


    【解决方案1】:

    写成++ 1.0 意味着++1.0(Double 类)的一元运算符。但是,在 Scala 中,一元运算符仅限于 ! ~ - +。所以没有办法实现你想要的语法。

    但你仍然可以使用括号:

    class ExampleStore extends Store {
      val a = ++(1.0)
      val b = ++(2.0)
      val c = ++(3.0)
    }
    

    【讨论】:

    • 编译器应该知道 ++ 不是一元运算符,因为一元运算符列表是有限的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-03
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    相关资源
    最近更新 更多