By this answer https://stackoverflow.com/a/1759565/11217621, I know in Java it is possible to do something like
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
}
where <U, V>
for the bar
method are independent from the class parametric type.
I have a simple data class in Java like
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);
}
}
...in such way that from an original DataPoint<Long>
, I apply some mapping function to the value
field, and the value turns into a Double. By using the method withNewValue
there is no problem to instantiate a new DataPoint<Double>
public DataPoint<Double> map(DataPoint<Long> dataPoint) {
double phase = (double) currentStep / numSteps;
return dataPoint.withNewValue(phase);
}
I need to migrate this to Scala, and I can't figure out how to do it. I'm trying to do something like:
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)
}
...which does not compile. Also tried several combinations following the official documentation about Scala covariance and contravariance but I'm still in my first steps with Scala.