How to decorate the Scala Int class with a custom impicit to convert to binary String

118 views Asked by At

I want to use the following method:

 def toBinary(i : Int, digits: Int = 8) =
                String.format("%" + digits + "s", i.toBinaryString).replace(' ', '0')

and turn it into a implicit conversion in order to "decorate" the scala Int class, RichInt so to achieve the following :

3.toBinary     //> res1: String = 00000011
3.toBinary(8)  //> res1: String = 00000011

instead of the call toBinary(3)

How can i achieve this ?

[EDIT] After looking to the link sugested i got the following which works

implicit class ToBinaryString(i :Int ) {
    def toBinary(digits: Int = 8) =
                String.format("%" + digits + "s", i.toBinaryString).replace(' ', '0')
  }

  3.toBinary(8)                                   //> res2: String = 00000011

I can't use it though without the default parameter, i would like to be able to write 3.toBinary

1

There are 1 answers

4
g-t On BEST ANSWER
object A extends App {
  implicit class RichInt(i: Int) {
    def toBinary(digits: Int = 8): String =
      String.format("%" + digits + "s", i.toBinaryString).replace(' ', '0')
  }

  println(3.toBinary(6))
}

Prints:

000011

// EDIT If you want to call 3.toBinary without parenthesis I guess you have to provide a method without parameters:

object A extends App {
  implicit class RichInt(i: Int) {
    def toBinary(digits: Int): String =
      String.format("%" + digits + "s", i.toBinaryString).replace(' ', '0')

    def toBinary: String = toBinary(8)
  }

  println(3.toBinary)
  println(3.toBinary(6))
}

This one works for me but I'm not Scala expert so there might be better way of doing this.