1

In Scala you can do Monkey Patching using implicits but yesterday I saw this example in ruby wih Fixnum, it's a silly thing but I would like to implement it in scala

class Fixnum

  def to_roman
    'I'*self #only works until 3, but only for this purpose 
  end

   def +(other)
      self - other
   end
end


puts 2.to_roman #This prints "II"
puts 1 + 1 #This prints 0

however in scala I can not make to work the + (inverse) method

object TestImplicits extends App {

  implicit class ReverseInt(val original: Int) extends AnyVal {

    def toRoman = { "I" * original }

    def +(other:Int){
      original - other
    }
  }

  println(5.toRoman) // prints IIIII
  println( 5 + 3 )  // prints 8

}

Also it is better that scala does't have global monkey patching like Ruby?

2 Answers 2

2

Scala will only attempt to find an implicit conversion for methods that aren't found. Since Scala finds a Int.+ method, it won't try to look for an implicit conversion, as opposed to toRoman, where Scala doesn't find the method and thus will search for an implicit conversion from Int to some type with a toRoman method.

1

This comes close:

class WrappedInt(val n: Int) {
  def + (other: Int): Int = {
    n - other
  }
}
implicit def unpack(wi: WrappedInt): Int = {
  wi.n
}

// usage
val wrapped = new WrappedInt(5)
println(wrapped + 3)  // performs 5 - 3
println(wrapped * 2)  // 5 * 2 (`unpack` is called first)

Note however that if you pass a WrappedInt into a method that expects an Int, the method will operate on the unwrapped value, so the "patch" won't be active inside the method:

def addOne(n: Int) = {
  n + 1
}
println(addOne(new WrappedInt(5)))  // Prints 6 (no patch)

I think it's better not to allow global patching - it's very dangerous because it there's no indication something has been patched if you're looking at a class in isolation. Everyone on a project will need to learn and memorize all these things that happen invisibly. And if you're working on multiple projects, you'll need to remember which project has which patch. With Scala, third-party implicits must be explicitly imported, so there's some indication in the current file or scope that something special is going on.

Ruby has refinements, but they don't seem very popular, probably because patching is so easy and ingrained in the culture.

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.