anquegi anquegi - 13 days ago 5
Ruby Question

Scala Monkey Patching Compared to Ruby

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?

Answer

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.

Comments