如何将单个字符转换为Scala';什么是Char对象?
将单个字符转换为Scala的字符对象的最简单、最简洁的方法是什么 我找到了以下解决方案,但不知何故,它似乎并不令我满意,因为我相信本应能够以更优雅的Scala方式解决此问题,而无需使用不必要的转换和特定于数组的操作:如何将单个字符转换为Scala';什么是Char对象?,scala,char,type-conversion,character,arrays,Scala,Char,Type Conversion,Character,Arrays,将单个字符转换为Scala的字符对象的最简单、最简洁的方法是什么 我找到了以下解决方案,但不知何故,它似乎并不令我满意,因为我相信本应能够以更优雅的Scala方式解决此问题,而无需使用不必要的转换和特定于数组的操作: scala> "A".toCharArray.head res0: Char = A 你可以用scala的 此外,以下内容是有效的,可能是您正在寻找的内容: scala> "a".charAt(0) res4: Char = a 有很多方法可以做到这一点。以下是一些
scala> "A".toCharArray.head
res0: Char = A
你可以用scala的
此外,以下内容是有效的,可能是您正在寻找的内容:
scala> "a".charAt(0)
res4: 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
通过一个通用接口运行,该接口必须对字符进行装箱,而.charAt(0)
和(0)
则不需要,因此后者大约快3倍
'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