9

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

2
  • 2
    Use == (or even === here), not is. is is for type checking (instanceof in Java). kotlinlang.org/docs/reference/typecasts.html, kotlinlang.org/docs/reference/equality.html Commented Aug 16, 2017 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!! Commented Aug 16, 2017 at 16:31

2 Answers 2

14

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

Sign up to request clarification or add additional context in comments.

1 Comment

You could alternatively use === though it's essentially the same thing when it comes to enums
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.