Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala implicit conversion not getting applied on Java argument pattern

Tags:

java

scala

I have given the static method

static void foo(Object... params)

in the Java class Bar and plan to call it as follows:

Bar.foo('x')

Which won't work beacause the method expects a Java character and somehow, the existing implicit conversion is not applied.

Bar.foo('x' : Character)
Bar.foo(new Character('x'))

will both do the trick, but hurt readability. Putting those constructs in an implicit conversion

implicit def baz(c : Char) = c : Character

does not work and I don't understand why. So my questions: What is the problem here? Is there a fix?

like image 679
Jin Avatar asked Jul 23 '14 14:07

Jin


2 Answers

The compiler is very specific about why it will not use any of these implicits:

error: the result type of an implicit conversion must be more specific than AnyRef

Object is a synonym for AnyRef, and becaue that is the value it needs to call foo it refuses to apply any implicit conversions.

However, you can define a wrapper around Bar.foo to enable you to use literal characters:

def barFoo(chars: Character*) = Bar.foo(chars.toArray: _*)
barFoo('x')
like image 76
wingedsubmariner Avatar answered Oct 17 '22 16:10

wingedsubmariner


The only variables that can be cast to an Object type are those which are class instance. That exclude basic type like int, boolean, double. These one need to be transform, respectively to the type : Integer, Boolean, Double.

like image 21
Moebius Avatar answered Oct 17 '22 17:10

Moebius