加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala,无法实现泛型java方法

发布时间:2020-12-16 19:18:25 所属栏目:安全 来源:网络整理
导读:我想实现一个在 scala中使用泛型的 java方法(2.9.2).但是我失败了…… Java接口方法: public T extends Number void setAttribute(KeyT key,Number value); 想要实现该方法的Scala代码: def setAttribute[T : Number](key: Key[T],value: Number) = { setA
我想实现一个在 scala中使用泛型的 java方法(2.9.2).但是我失败了……

Java接口方法:

public <T extends Number> void setAttribute(Key<T> key,Number value);

想要实现该方法的Scala代码:

def setAttribute[T <: Number](key: Key[T],value: Number) = {
  setAttributeLocal(key,value)  }

private def setAttributeLocal[T](key: Key[T],value: T) = {
  val stringValue = ConvertUtils.convert(value,classOf[String]).asInstanceOf[String]
  session = session + (key.getValue() -> stringValue)
}

关键看起来像:

public class Key<T>

但这不编译.

[error]  found   : mypackage.Key[T]
[error]  required: mypackage.Key[java.lang.Number]
[error] Note: T <: java.lang.Number,but Java-defined class Key is invariant in type T.
[error] You may wish to investigate a wildcard type such as `_ <: java.lang.Number`. (SLS 3.2.10)
[error]     setAttributeLocal(key,value)

我无法弄清楚问题是什么.有什么建议/想法吗?

greez
GarfieldKlon

解决方法

看来编译器对你对setAttributeLocal的调用不满意. setAttributeLocal需要一个Key [Number],但是你提供了一个Key [_<:T].在Java-Land中,这意味着您正在尝试传递密钥<? extends Number>关键字< Number>.

建议是让setAttributeLocal接受Key<? extends Number>或Key [_&lt ;: Number],具体取决于它是Java还是Scala定义的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读