8

How do I filter by an enum class in kotlin? (just learning) In the code below the enum class defined earlier in the file is PayStatus{PAID,UNPAID}.

fun nextRentDate(): LocalDate? {
            return rentPaymentSchedule.
                    filter { it.value.paymentStatus is PayStatus.UNPAID}.
                    minBy { it.value.date.toEpochDay() }?.value?.date
        }

I get the error: Kotlin:

Incompatible types: PayStatus.UNPAID and Enum

arne.z
  • 3,242
  • 3
  • 24
  • 46
mleafer
  • 825
  • 2
  • 7
  • 15
  • 2
    Use `==` (or even `===` here), not `is`. is is for type checking (instanceof in Java). https://kotlinlang.org/docs/reference/typecasts.html, https://kotlinlang.org/docs/reference/equality.html – JB Nizet Aug 16 '17 at 16:28
  • nice, yea i had tried `==` but was getting a different error, the root problem was that I had defined enum class in both the state file, and the contract file, so it was getting overridden by the wrong file defined enum class. all sorted, thanks!! – mleafer Aug 16 '17 at 16:31

2 Answers2

14

You must use the == operator when checking for enum values !

Stefano.Maffullo
  • 801
  • 8
  • 21
  • You could alternatively use `===` though it's essentially the same thing when it comes to enums – Mark Jan 19 '19 at 02:02
3

The is keyword should be used for type comparison, as described here. Using the operator for comparisons isn't possible as the compiler complains:

'is' over enum entry is not allowed, use comparison instead

Comparison in Kotlin comes in two flavors: == and ===

The first option, == is compiled down to equals(), whereas the latter, ===, is equivalent to Java's == (comparing references).

As we know, this doesn't really make a difference with enums, as you can read in this answer.

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196