简体   繁体   English

Scala隐式转换未应用到Java参数模式

[英]Scala implicit conversion not getting applied on Java argument pattern

I have given the static method 我给了静态方法

static void foo(Object... params)

in the Java class Bar and plan to call it as follows: 在Java类Bar中,并计划如下调用它:

Bar.foo('x')

Which won't work beacause the method expects a Java character and somehow, the existing implicit conversion is not applied. 由于该方法需要Java字符,因此该方法不起作用,并且不应用现有的隐式转换。

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. ObjectAnyRef的同义词,因为这是它需要调用foo的值,因此它拒绝应用任何隐式转换。

However, you can define a wrapper around Bar.foo to enable you to use literal characters: 但是,您可以在Bar.foo周围定义包装器,以使您可以使用文字字符:

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. 不包括基本类型,如int,boolean,double。 These one need to be transform, respectively to the type : Integer, Boolean, Double. 这些分别需要转换为以下类型:整数,布尔值,双精度型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM