0

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
0

3 Answers 3

6

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.

4

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
3

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.::

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.