Search code examples
scalapojo

POJO's in Scala


I have the following 2 classes in Java

public class DataPoint<T> {

    public long timeStampMs;
    public T value;

    public DataPoint() {}

    public DataPoint(long timeStampMs, T value) {
        this.timeStampMs = timeStampMs;
        this.value = 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);
    }
}

and

public class KeyedDataPoint<T> extends DataPoint<T>{

    public String key;

    public KeyedDataPoint() {}

    public KeyedDataPoint(String key, long timeStampMs, T value) {
        super(timeStampMs, value);
        this.key = key;
    }

    public <R> KeyedDataPoint<R> withNewValue(R newValue){
        return new KeyedDataPoint(this.key, this.timeStampMs, newValue);
    }

}

I need to translate then into Scala:

class DataPoint[T] (@BeanProperty val timeStampMs: Long, @BeanProperty val value: T) {
    def withNewValue[R](value: R): DataPoint[R] = new DataPoint[R](timeStampMs, value)
    def withKey(key: String): KeyedDataPoint[T] = new KeyedDataPoint(key, timeStampMs, value)
}

class KeyedDataPoint[T](@BeanProperty val key: String,
                        @BeanProperty override val timeStampMs: Long,
                        @BeanProperty override val value: T) extends DataPoint (timeStampMs, value) {
}

The classes need to qualify as POJO's, but I can't figure out how to get it. If I provide a no-args primary constructor, then I don't know how to provide the multiple args auxiliary constructor, and viceversa ...if I leave the primary constructor for several arguments, then I don't know how to provide the no-args constructor demanded for POJO compliance. Any help?


Solution

  • class KeyedDataPoint[T](@BeanProperty val key: String,
                            @BeanProperty override val timeStampMs: Long,
                            @BeanProperty override val value: Option[T]) extends DataPoint (timeStampMs, value) {
    }  
    
    class DataPoint[T] (@BeanProperty val timeStampMs: Long, @BeanProperty val value: Option[T]) {
        def this() {
          this(0, None);
        }  
        def withNewValue[R](value: Option[R]): DataPoint[R] = new DataPoint(timeStampMs, value)
        def withKey(key: String): KeyedDataPoint[T] = new KeyedDataPoint(key, timeStampMs, value)
    }