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?
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')
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With