简体   繁体   English

如何在 Scala 中实现返回用数组参数化的泛型类型的 Java 方法?

[英]How to implement Java method returning a generic type parametrized with array in Scala?

I have an interface with the following method in Java:我在 Java 中有一个具有以下方法的接口:

<E> Encoder1<E[]> arrayArg(Encoder1<? super E> elemEncoder);

I'm trying to implement it in Scala with the following declaration:我正在尝试使用以下声明在 Scala 中实现它:

override def arrayArg[E](elemEncoder: Encoder1[_ >: E]): Encoder1[Array[E]]

I get the following error:我收到以下错误:

Error:(38, 16) overriding method arrayArg in trait Encoders of type [E](elemEncoder: redradishes.encoder.expr.Encoder1[_ >: E])redradishes.encoder.expr.Encoder1[Array[E with Object]];
 method arrayArg has incompatible type
  override def arrayArg[E](elemEncoder: Encoder1[_ >: E]): Encoder1[Array[E]] = ???
               ^

What is wrong with my Scala method signature?我的 Scala 方法签名有什么问题?

Please see this: https://issues.scala-lang.org/browse/SI-4390请看这个: https : //issues.scala-lang.org/browse/SI-4390

I'm not sure I fully understand why, but you need to specify E with Object in return value for it to compile.我不确定我是否完全理解为什么,但是您需要在返回值中指定E with Object才能进行编译。 The error informs you about that.该错误会通知您。 Probably this is because in java you cannot use primitive types ( AnyVal ) as the generic parameter, but in scala you can so you need to specify that E extends Object to align it with Java rules.可能这是因为在 java 中你不能使用原始类型 ( AnyVal ) 作为泛型参数,但在 scala 中你可以,所以你需要指定E extends Object以使其与 Java 规则对齐。 Still I'm not sure why this situation is so special.我仍然不确定为什么这种情况如此特殊。

If you are uncomfortable with Object , E with AnyRef also seem to work.如果您对Object感到不舒服, E with AnyRef似乎也可以工作。

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

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