Creating a `**` statement for a Scala statement?

I really like the ** syntax for pow , available in many languages ​​(like Python).

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

My Int attempt is only one:

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

(see his IDEone failure)

+9
operators scala operator-overloading pow
source share
4 answers

this works for me: (problem number 1 pow is defined by doubling, problem number 2 extending any value) (also it makes no sense to have these backreferences in the method?)

 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) } } 
+13
source share

This answer is delayed for 2 years, but for others I would like to indicate that the accepted answer is unnecessarily distributed from AnyVal.

There is only a minor bug that needs to be fixed in the original answer. The def ** method requires only one parameter, that is, an exponent, since the base is already passed in the constructor, and not as in the source code. Fixing this and removing the backward steps results in:

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

How it works here .

The Scala compiler will distinguish Int to PowerInt only if the method that is called on it is undefined. That is why you do not need to exit AnyVal.

Behind the scenes, Scala is looking for an implicit class whose constructor argument type matches the type of object that is being executed. Since an object can have only one type, implicit classes cannot have more than one argument in its constructor. Moreover, if you define two implicit classes with the same constructor type, make sure that their functions have unique signatures, otherwise Scala would not know which class would belong and complain about ambiguity.

+14
source share

There is a way to make the solution more universal using the Numeric typeclass:

 implicit class PowerOp[T: Numeric](value: T) { import Numeric.Implicits._ import scala.math.pow def **(power: T): Double = pow(value.toDouble(), power.toDouble()) } 
+3
source share

This is my solution using recursion (so I don't need import scala.Math.pow ):

 object RichInt { implicit class PowerInt(val base:Double) { def ** (pow:Double):Double = if (pow==0) 1 else base*(base**(pow-1)) } def main(args:Array[String]){ println(2.0**3.0) //8.0 println(2.0**0.0) //1.0 } } 
0
source share

All Articles