【发布时间】:2019-03-17 20:34:03
【问题描述】:
通过这个答案https://stackoverflow.com/a/1759565/11217621,我知道在 Java 中可以做类似的事情
public class MyClass<S, T> {
public void foo(Set<S> s, Set<T> t); //same type params as on class
public <U, V> void bar(Set<U> s, Set<V> t); //type params independent of class
}
其中bar 方法的<U, V> 独立于类参数类型。
我有一个简单的 Java 数据类,比如
public class DataPoint<T> {
public long timeStampMs;
public T value;
public <R> DataPoint<R> withNewValue(R newValue){
return new DataPoint(this.timeStampMs, newValue);
}
public KeyedDataPoint withKey(String key){
return new KeyedDataPoint(key, this.timeStampMs, this.value);
}
}
...以这样的方式,从原始的DataPoint<Long>,我将一些映射函数应用于value 字段,并且值变成了 Double。通过使用withNewValue方法实例化new DataPoint<Double>是没有问题的
public DataPoint<Double> map(DataPoint<Long> dataPoint) {
double phase = (double) currentStep / numSteps;
return dataPoint.withNewValue(phase);
}
我需要将它迁移到 Scala,但我不知道该怎么做。我正在尝试做类似的事情:
class DataPoint[T1] (val timeStampMs: Long, val value: T1) {
def withNewValue(value: T2): DataPoint[T2] = new DataPoint[T2](this.timeStampMs, value)
def withKey(key: String): KeyedDataPoint[T1] = new KeyedDataPoint(key, this.timeStampMs, this.value)
}
...无法编译。还尝试了有关 Scala 协变和逆变的官方文档的几种组合,但我仍处于使用 Scala 的第一步。
【问题讨论】:
-
如果您将第一个方法声明为
withNewValue[T2]并添加KeyedDataPoint的定义,那么您的示例似乎编译得很好,没有任何方差注释。不确定实际问题是什么。 -
谢谢安德烈,成功了!
标签: scala generics apache-flink