【问题标题】:Using unicode symbol as an infix operator in Scala在 Scala 中使用 unicode 符号作为中缀运算符
【发布时间】:2011-11-14 14:03:58
【问题描述】:
有谁知道为什么下面的代码不能将 ∙ 识别为有效的中缀运算符?
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
【问题讨论】:
标签:
scala
operators
infix-notation
【解决方案1】:
将∙ 定义为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。
不过,不确定你想要达到什么目的。
【解决方案2】:
简单地说,因为它不是。它是object 和class,但不是方法,只有方法可以是运算符(中缀与否)。
作为一个对象,你可以在模式匹配上使用它:
case a ∙ b =>
作为一个类,如果它有两个类型参数,它将在类型声明中使用它:
type X = Int ∙ String
【解决方案3】:
这不是因为使用了 unicode 符号。我知道没有中缀构造函数语法。因此,如果您想使用中缀语法创建对象,您可以按照 Emil 的建议(将 ∙ 方法添加到 Term 或 I)或使用隐式转换:
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.::