Question

Does anyone know why the following code doesn't recognize ∙ as a valid infix operator?

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
Was it helpful?

Solution

Define as method on 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)
}

Now I() ∙ I() will work, returning II.


Not sure what you are trying to achieve, though.

OTHER TIPS

To put it simply, because it is not. It is an object and a class, but not a method, and only methods can be operators (infix or not).

As an object, you can use it on pattern matches:

case a ∙ b =>

As a class, if it had two type parameters, it would use it on type declarations:

type X = Int ∙ String

This is not due to the use of the unicode symbol. There is no infix constructor syntax that I'm aware of. So if you want to create an object with an infix syntax you can do what Emil suggests (adding the method to Term or I) or use an implicit conversion:

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)
}
  • The implicit version is more like Predef.any2ArrowAssoc to create tuples: 1 -> 2
  • Adding the method is more like List.::
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top