【问题标题】: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】:

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

      作为一个对象,你可以在模式匹配上使用它:

      case a ∙ b =>
      

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

      type X = Int ∙ String
      

      【讨论】:

        【解决方案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.::

        【讨论】:

          猜你喜欢
          • 2014-07-16
          • 1970-01-01
          • 1970-01-01
          • 2014-02-24
          • 1970-01-01
          • 2012-05-01
          • 2011-11-16
          • 2015-09-22
          • 2014-12-03
          相关资源
          最近更新 更多