Why am I getting a compilation error here?


#1

Here is my code so far:

class Bucket {
  val MAX_SAMPLES_PER_BUCKET : Long = 1024

    var sum : Double = 0.0
    var count : Long = 0

    var threshold : Double? = null
    var left : Bucket? = null
    var right : Bucket? = null

    fun addSample(sample : Double) {

           if (threshold == null) {
           count ++
           sum += sample
           if (count == MAX_SAMPLES_PER_BUCKET) {
                   threshold = sum / count
                   left = Bucket()
                   right = Bucket()
           }
           } else {
           if (sample < threshold) {   <---- Compilation error

           }
           }
  }
  }

However I’m getting the following compilation error on the ‘<’:

None of the following functions can be called with the arguments supplied: public open fun compareTo(val other : jet.Double) : jet.Int defined in <builtin>.<root>.jet.Double public final fun compareTo(val other : jet.Int) : jet.Int defined in <builtin>.<root>.jet.Double public final fun compareTo(val other : jet.Float) : jet.Int defined in <builtin>.<root>.jet.Double public final fun compareTo(val other : jet.Short) : jet.Int defined in <builtin>.<root>.jet.Double public final fun compareTo(val other : jet.Long) : jet.Int defined in <builtin>.<root>.jet.Double public final fun compareTo(val other : jet.Char) : jet.Int defined in <builtin>.<root>.jet.Double public final fun compareTo(val other : jet.Byte) : jet.Int defined in <builtin>.<root>.jet.Double

I don’t understand why this would be, aren’t both values Doubles?


#2

Ah, ok - figured it out just after posting this, threshold was a var not a val.

What is the recommended way to do this?  Should I declare a “currentThreshold” val at the start of the method and put “threshold” in it?  Seems a bit messy.


#3

I think its because threshold is nullable. (Ideally the compiler would be clever enough to spot this and recommend using threshold!! or something).

Try using this (which will cast threshold to be not-nullable)

if (threshold  != null && sample < threshold)

or append !! to threshold