简单的惯用法转换Java类实现Comparator& amp;与Scala相比?

时间:2016-06-01 03:06:50

标签: scala jfreechart comparator comparable

我有一个现有的JFreeChart插件类,它不会转换为Scala v2.11,它比看起来更棘手。 Java是:

package x;
import org.apache.commons.lang.NotImplementedException;
import org.jfree.data.time.RegularTimePeriod;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;

public final class IntervalJFreeChart extends RegularTimePeriod implements  Comparator, Comparable, Serializable {

final int width;
final long seqNo;

final long firstMilli;
final long lastMilli;

public IntervalJFreeChart(Date time, int w) {
    MathContext mc = new MathContext(16, RoundingMode.FLOOR);
    width = w;
    BigDecimal wbd =  new java.math.BigDecimal(""+w);
    wbd.setScale(120, RoundingMode.FLOOR);
    BigDecimal bd = new java.math.BigDecimal(time.getTime());
    bd.setScale(120, RoundingMode.FLOOR);
    seqNo = bd.divide(wbd, mc).longValue();

    BigDecimal seqBd = new java.math.BigDecimal(seqNo);
    seqBd.setScale(120, RoundingMode.FLOOR);
    firstMilli = seqBd.multiply(wbd).longValue();
    lastMilli = firstMilli + w -1;
}

@Override
public IntervalJFreeChart previous() {
    return new IntervalJFreeChart(new Date(firstMilli - width), width); 
}

@Override
public IntervalJFreeChart next() {
    return new IntervalJFreeChart(new Date(lastMilli + width), width); 
}

@Override
public long getSerialIndex() {
    return this.seqNo;
}

@Override
public void peg(Calendar calendar) {
    throw new NotImplementedException("peg()");
}

@Override
public long getFirstMillisecond() {
    return firstMilli;
}

@Override
public long getFirstMillisecond(Calendar calendar) {
    calendar.setTimeInMillis(firstMilli);
    return firstMilli;
}

@Override
public long getLastMillisecond() {
    return lastMilli;
}

@Override
public long getLastMillisecond(Calendar calendar) {
    calendar.setTimeInMillis(lastMilli);
    return lastMilli;
}

@Override
public int compareTo(Object o) {
    return compare(this, o);
}

@Override
public int compare(Object o1, Object o2) {
    if (o2 instanceof IntervalJFreeChart) {
        final IntervalJFreeChart m1 = (IntervalJFreeChart)o1;
        final IntervalJFreeChart m2 = (IntervalJFreeChart)o2;
        final int diff = Long.valueOf(m1.seqNo).compareTo(m2.seqNo);
        if (diff > 0) return 1;
        if (diff < 0) return -1;
        return 0;
    }
    throw new RuntimeException("MilliInterval: compare error : "); 
}
}

我看到的问题是:抽象类RegularTimePeriod实现了java的Comparable接口而没有为它指定类型参数。 因此,Scala实现需要:具体的Comparator和Comparable。

建议非常感谢。

1 个答案:

答案 0 :(得分:1)

由于该类实际仅与IntervalJFreeChart进行比较,因此只需使用Comparable[IntervalJFreeChart]