在Scala中使用unicode符号作为中缀运算符

时间:2011-11-14 14:03:58

标签: scala operators infix-notation

有谁知道为什么下面的代码不能将∙识别为有效的中缀运算符?

object Main extends App {
  val c = (I() ∙ I())
}

sealed abstract class Term 
case class I() extends Term
case class ∙(x: Term, y: Term) extends Term

3 个答案:

答案 0 :(得分:6)

定义为I上的方法。

sealed abstract class Term 
case class II(x: Term, y: Term) extends Term
case class I() extends Term {
    def ∙(o: Term) = II(this, o)
}

现在I() ∙ I()将有效,返回II


不确定你想要实现的目标。

答案 1 :(得分:4)

简单地说,因为它不是。它是objectclass,但不是方法,只有方法可以是运算符(中缀或非中缀)。

作为对象,您可以在模式匹配中使用它:

case a ∙ b =>

作为一个类,如果它有两个类型参数,它将在类型声明上使用它:

type X = Int ∙ String

答案 2 :(得分:3)

这不是因为使用了unicode符号。我没有注意到中缀构造函数语法。因此,如果您想创建一个具有中缀语法的对象,您可以执行Emil建议的操作(将方法添加到TermI)或使用隐式转换:

sealed abstract class Term 
case class I() extends Term 
case class ∙(x: Term, y: Term) extends Term

class Ctor_∙(x: Term) {
  def ∙(y: Term): ∙ = new ∙(x, y)
}  

object Term {
  implicit def to_∙(x: Term): Ctor_∙ = new Ctor_∙(x)
}
  • 隐式版本更像Predef.any2ArrowAssoc来创建元组:1 -> 2
  • 添加方法更像List.::