Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char or String -> Unicode value in Scala?

Tags:

unicode

scala

So I'm working through a few of the exercises in "Scala for the Impatient" and one of them is:

Write a for loop for computing the product of the Unicode codes of all letters in a string. For example, the product of the characters in "Hello" is 9415087488 L.

The next problem is to do the same, but without a for loop - it hints that we should check StringOps in Scaladoc.

I checked the RichChar and StringOps section in Scaladoc, and perhaps I'm misreading or looking in the wrong places, but I can't find anything that gets me to match their output. I've thus far tried:

scala> x.foldLeft(1)(_ * _.toInt) res0: Int = 825152896  scala> x.foldLeft(1)(_ * _.getNumericValue) res5: Int = 2518992  scala> x.foldLeft(1)(_ * _.intValue()) res6: Int = 825152896  scala> var x = 1 x: Int = 1  scala> for (c <- "Hello") x *= c.toInt  scala> x res12: Int = 825152896 

Which does not match their output.

How do I do this, in both the for and non-for way?

Thanks!

like image 809
adelbertc Avatar asked Jun 23 '12 00:06

adelbertc


People also ask

What is string literal in Scala?

A string literal is a sequence of characters in double quotes. The characters are either printable unicode character or are described by escape sequences. If the string literal contains a double quote character, it must be escaped, i.e. "\"" . The value of a string literal is an instance of class String .

How do you declare a character in Scala?

Scala Char |(x: Char) method with exampleThe |(x: Char) method is utilized to find the bit-wise OR of the stated character value and given 'x' in the argument list. Return Type: It returns the bit-wise OR of the stated character value and given 'x'.

What is escape character in Scala?

An escape value is a backslash with a character that will escape that character to execute a certain functionality. We can use these in character and string literals. We have the following escape values in Scala: Escape Sequences. Unicode.

What is Unicode in Java string?

Unicode is an international standard of character encoding which has the capability of representing a majority of written languages all over the globe. Unicode uses hexadecimal to represent a character. Unicode is a 16-bit character encoding system. The lowest value is \u0000 and the highest value is \uFFFF.


1 Answers

When you do x.foldLeft(1)(_ * _.toInt), the result type will be inference to an Int, but 9415087488 is too large for an Int to store it.

So you need to tell Scala using Long to store it.

scala> val x = "Hello" x: java.lang.String = Hello  scala> x.foldLeft(1L)(_ * _.toInt) res1: Long = 9415087488  scala> var x: Long = 1 x: Long = 1  scala> for (c <- "Hello") x *= c.toInt  scala> x res7: Long = 9415087488 
like image 92
Brian Hsu Avatar answered Sep 20 '22 14:09

Brian Hsu