0

I don't get the following results: I have a function alreadyDoneToday():Boolean. While debugging I noticed an odd behavior. The expression itself returns true, but false when wrapped inside the function.

enter image description here

var lastDone: Date? = null
...
fun today(): Date {
    var calendar = Calendar.getInstance()
    return toDateWithoutTime(calendar.time)
}

My solution was now to add a null-check:

fun alreadyDoneToday():Boolean{
    return lastDone != null && lastDone!! == today()
}

I was kinda hoping that I could compare a nullable to a not nullable. Apparently not. However the debugger output is really misleading.

Any clues?

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
Matthias
  • 1,267
  • 1
  • 15
  • 27
  • 1
    What type does `lastDone` have and what is that `today()`-function doing? Please share the declaration or the whole code around it. Note also that when you debug the `toString()`-method or lazy evaluations might influence the behaviour or result. You may rather want to setup a unit test instead. – Roland Jan 25 '19 at 11:26
  • *My solution was now to add an null-check* where is the null check? *I could compare a nullable to a not nullable* which is the nullable and which the not nullable? Your question is not clear. – forpas Jan 25 '19 at 11:30
  • copy & paste error. updated my post – Matthias Jan 25 '19 at 11:32
  • can't reproduce it... probably there is something else around that influences the result... can you share the whole code? better yet: only those parts that deal with `lastDone`? – Roland Jan 25 '19 at 11:36
  • 1
    Cannot reproduce it here either. Are you sure you don't have any background threads modifying `lastDone`? What is the implementation of `toDateWithoutTime()`? – m0skit0 Jan 25 '19 at 11:44
  • 1
    Just as a side note, don't use the old `Date` api anymore, but better use `java.time` (of course only if you happen to compile your kotlin to java code) – Lino Jan 25 '19 at 11:50
  • Can't reproduce here, either.  Given the code above, IntelliJ is fine with `fun alreadyDoneToday() = lastDone == today()`.  And yes, in general, you *can* use `==` to compare nullable and non-nullable values. – gidds Jan 25 '19 at 12:54
  • 1
    You can definitely compare nullables and non nullables: `val b0: Boolean = true` > `val b1: Boolean? = true` > `b0 == b1` > `true` tested on the REPL – Danilo Pianini Jan 25 '19 at 14:58

0 Answers0