Saturday 11 July 2009

Implicits (base converter)

Defining a method as 'implicit' means that it becomes global to that package. Use with extreme care!!

Here is an integer base converter which I wrote:
Note how we can now call methods on the integers themselves

object Types {
case class NumberConverter(val i : Int) {
def octal = BaseBuilder(i, 8)
def hex = BaseBuilder(i, 16)
def mybase(base : Int) = BaseBuilder(i, base)
}

def BaseBuilder(i : Int, base : Int) : String = {
i match {
case 0 => ""
case _ => BaseBuilder(i/base, base) + baseToCharacter(i % base)
}
}

def baseToCharacter(i : Int) : String = {
return "" + {
if ( (0 to 9).contains(i) ) {
i
} else {
(i + 55).toChar
}
}
}

implicit def baseConverter(i : Int) : NumberConverter = NumberConverter(i)

def main(args : Array[String]) : Unit = {
println( 29 )
println( 29.hex )
println( 29.octal )
println( 15.mybase(16) )
println( 129.mybase(2) )
}
}

No comments:

Post a Comment