How to return a "primitive Java char" from Scala?

If I write:

def getShort(b: Array[Byte]): Short 

in Scala, I get a primitive short text in Java, and that's fine. But if I write:

def getChar (b: Array [Byte]): Char

I get a scala.Char object that does NOT fit. And if I write:

 def getChar(b: Array[Byte]): Character 

I get java.lang.Character, which is also wrong.

If Scala "Char" is not Java "Char", and Scala "Character" is not Java "Char", then what remains?

+4
source share
4 answers

You're wrong; Char is a Java char primitive. Note:

 scala> class IsPrimitiveChar { | def myChar(i: Int): Char = i.toChar // I am clearly a Char, whatever that is! | } defined class IsPrimitiveChar scala> :javap IsPrimitveChar Compiled from "<console>" public class IsPrimitiveChar extends java.lang.Object implements scala.ScalaObject{ public char myChar(int); // Look, it returns a char! public IsPrimitiveChar(); } scala> :javap -c -private IsPrimitiveChar Compiled from "<console>" public class IsPrimitiveChar extends java.lang.Object implements scala.ScalaObject{ public char myChar(int); Code: 0: iload_1 1: i2c // Look, primitive int to char conversion in bytecode! 2: ireturn // And that all! 

To work, by the way, you need to have tools.jar in the classpath for :javap . It is included in the Sun / Oracle JVM.

+10
source

I believe that both will decide the primitive.

 scala> def getShort(b: Array[Byte]): Short = 0 getShort: (b: Array[Byte])Short scala> getShort(Array(1)) res10: Short = 0 scala> getShort(Array(1)).getClass().getName() res11: java.lang.String = short scala> def getChar(b: Array[Byte]): Char = 'a' getChar: (b: Array[Byte])Char scala> getChar(Array(1)) res13: Char = a scala> getChar(Array(1)).getClass().getName() res14: java.lang.String = char 
+3
source

Scala Char is scala.Char , which is similar to Char , just like AnyRef is the same as Object . For the JVM, this is Char , Scala, this is scala.Char .

+3
source

java.lang.Character is just as good for Java as primitive for most purposes. If you really need a primitive, you can simply return charValue () off object

-1
source

Source: https://habr.com/ru/post/1388473/


All Articles