DJ Gruby
DJ Gruby

Reputation: 179

How to convert a single character into Scala's Char object?

What is the simplest and the most concise method of converting a single character into Scala's Char object?

I have found the following solution, but somehow it seems unsatisfying to me, as I believe it should have been possible to resolve this problem in a more elegant Scala-way without using unnecessary conversions and array-specific operations:

scala> "A".toCharArray.head
res0: Char = A

Upvotes: 2

Views: 11296

Answers (2)

Rex Kerr
Rex Kerr

Reputation: 167891

There are a huge number of ways of doing this. Here are a few:

'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

If you use Scala much, the .head version is the cleanest and clearest; no messy stuff with numbers that might get off by one or which have to be thought about. But if you really need to do this a lot, head runs through a generic interface that has to box the char, while .charAt(0) and (0) do not, so the latter are about 3x faster.

Upvotes: 25

brebs
brebs

Reputation: 234

You can use scala's charAt.

scala> var a = "this"
a: String = this

scala> a.charAt(0)
res3: Char = t

Additionally, the following is valid and may be what you are looking for:

scala> "a".charAt(0)
res4: Char = a

Upvotes: 2

Related Questions