什么是 Scala 方式来实现这个 Java“byte[] to Hex"?班级 [英] What is/are the Scala way(s) to implement this Java "byte[] to Hex" class
本文介绍了什么是 Scala 方式来实现这个 Java“byte[] to Hex"?班级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对使用格式构建字符串的 Scala (2.8) 技术以及使这种功能在有用的地方(字节列表、字符串……?)轻松访问的有趣方法特别感兴趣.
I'm specifically interested in Scala (2.8) techniques for building strings with formats as well as interesting ways to make such a capability easily accessible where it's useful (lists of bytes, String, ...?)..
public class Hex {
public static String valueOf (final byte buf[]) {
if (null == buf) {
return null;
}
final StringBuilder sb = new StringBuilder(buf.length * 2);
for (final byte b : buf) {
sb.append(String.format("%02X", b & 0xff));
}
return sb.toString();
}
public static String valueOf (final Byteable o) {
return valueOf(o.toByteArray());
}
}
这只是一个学习练习(所以 Java 的实用性和实现不是问题.)
This is only a learning exercise (so the utility and implementation of the Java isn't a concern.)
谢谢
推荐答案
这不会像处理代码那样处理 null
.
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)
}
如果您希望能够处理可能为 null
的数组,则最好通过调用代码并执行以下操作来做到这一点:
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)
这篇关于什么是 Scala 方式来实现这个 Java“byte[] to Hex"?班级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文