Creating `**` power operator for Scala?

A T picture A T · Nov 3, 2013 · Viewed 17.9k times · Source

I quite like the ** syntax for pow, available in many languages (such as Python).

Is it possible to introduce this into Scala, without modifying the Scala 'base' code?

My attempt at an Int only one:

import scala.math.pow
implicit class PowerInt(i: Int) {
    def `**`(n: Int, b: Int): Int = pow(n, b).intValue
}

(see it failing on IDEone)

Answer

Stefan Kunze picture Stefan Kunze · Nov 3, 2013

this works for me: (problem#1 pow is defined on doubles, problem#2 extending anyval) (also there is no point in having those backticks in the methodname?)

import scala.math.pow

object RichIntt {

  implicit class PowerInt(val i:Double) extends AnyVal {
    def ** (exp:Double):Double = pow(i,exp)
  }

  def main(args:Array[String])
  {
    println(5**6)
  }

}