将单个字符转换为Scala的Char对象的最简单、最简洁的方法是什么?
我找到了以下解决方案,但不知何故我觉得它并不令人满意,因为我相信应该可以通过更优雅的 Scala 方式解决这个问题,而无需使用不必要的转换和数组-具体操作:
scala> "A".toCharArray.head
res0: Char = A
最佳答案
有很多方法可以做到这一点。这里有一些:
'A' // Why not just write a char to begin with?
"A"(0) // Think of "A" like an array--this is fast
"A".charAt(0) // This is what you'd do in Java--also fast
"A".head // Think of "A" like a list--a little slower
"A".headOption // Produces Option[Char], useful if the string might be empty
如果你经常使用 Scala,.head
版本是最干净、最清晰的;没有乱七八糟的东西,数字可能会差一个或必须考虑。但是,如果您真的需要经常这样做,head
会通过一个通用接口(interface)运行,该接口(interface)必须将 char 装箱,而 .charAt(0)
和 (0 )
不会,所以后者大约快 3 倍。
https://stackoverflow.com/questions/17154963/
相关文章:
javascript - 如何检查 Node js中的变量是否为空或未定义
reactjs - 为什么 "import { React } from ' react ';“不起
python - opencv 自动完成不适用于 pycharm
python - 如何在 Windows 命令提示符下运行 python 文件?
typescript - TypeError : (0 , next_sanity__WEBPACK
swift - 在 swift 4 的 for 循环中大于和小于等于