Scala Infix Notation – How to Use It

scala

Is it possible to call a method using infix notation?

For example, in Haskell, I could write the following function:

x `isAFactorOf` y = x % y == 0

and then use it like:

if 2 `isAFactorOf` 10 ...

Which in some cases allows for very readable code. Is anything similar to this possible in Scala? I searched for "Scala infix notation", but that term seems to mean something different in Scala.

Best Answer

Starting with version 2.10, Scala introduced implicit Classes to handle precisely this issue.

This will perform an implicit conversion on a given type to a wrapped class, which can contain your own methods and values.

In your specific case, you'd use something like this:

implicit class RichInt(x: Int) {
  def isAFactorOf(y: Int) = x % y == 0
}

2.isAFactorOf(10)
// or, without dot-syntax
2 isAFactorOf 10

Note that when compiled, this will end up boxing our raw value into a RichInt(2). You can get around this by declaring your RichInt as a subclass of AnyVal:

implicit class RichInt(val x: Int) extends AnyVal { ... }

This won't cause boxing, but it's more restrictive than a typical implicit class. It can only contain methods, not values or state.

Related Topic