Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

char

scala

If I write:

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

in Scala, I get a primitive short in Java, which is fine. But if I write:

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

I get a scala.Char object, which is NOT fine. And if I write:

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

I get a java.lang.Character, which ISN'T fine either.

If Scala "Char" isn't Java "char", and Scala "Character" isn't Java "char", then what is left?

like image 626
Sebastien Diot Avatar asked Dec 07 '22 17:12

Sebastien Diot


1 Answers

You're mistaken; Char is the Java primitive char. Observe:

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's all!

One needs to have tools.jar on the classpath for :javap to work, by the way. It's included with the Sun/Oracle JVMs.

like image 53
Rex Kerr Avatar answered Dec 09 '22 06:12

Rex Kerr