score:67

Accepted answer

This doesn't handle null in the same way as your code.

object Hex {

  def valueOf(buf: Array[Byte]): String = buf.map("%02X" format _).mkString

  def valueOf(o: Byteable): String = valueOf(o.toByteArray)

}

If you want to be able to handle possibly-null arrays, you might be better doing that from calling code and doing:

val bytes: Array[Byte] = // something, possibly null
val string: Option[String] = Option(bytes).map(Hex.valueOf)

score:5

You should use Scala's Option type instead of null. (This is tested with Scala 2.8.0.RC1)

object Hex {
  def valueOf (buf: Array[Byte]) = {
    if (null == buf) {
      None
    } else {
      val sb = new StringBuilder(buf.length * 2)
      for (b <- buf) {
        sb.append("%02X".format(b & 0xff))
      }
      Some(sb.toString())
    }
  }
  /*
  def valueOf(o: Byteable) = {
    return valueOf(o.toByteArray());
  }
  */
}

println(Hex.valueOf(Array(-3, -2, -1, 0, 1, 2, 3)))
println(Hex.valueOf(null))

score:9

Perhaps there are more elegant ways, but something like:

def valueOf(bytes : List[Byte]) = bytes.map{
  b => String.format("%02X", new java.lang.Integer(b & 0xff)) 
}.mkString

should work.


Related Query

More Query from same tag