6

I write code like bellow:

when(month){
        1 or 7 -> arrHoangDao = arrayListOf("Tý", "Sửu", "Tỵ", "Mùi")
        2 or 8 -> arrHoangDao = arrayListOf("Dần", "Mão", "Mùi", "Dậu")
        3 or 9 -> arrHoangDao = arrayListOf("Thìn", "Tỵ", "Dậu", "Hợi")
        4 or 10 -> arrHoangDao = arrayListOf("Ngọ", "Mùi", "Sửu", "Dậu")
        5 or 11 -> arrHoangDao = arrayListOf("Thân", "Dậu", "Sửu", "Mão")
        /* 6 or 12 is duplicate */
        6 or 12 -> arrHoangDao = arrayListOf("Tuất", "Hợi", "Mão", "Tị")
    }

I get the message is "duplicate in when". What does it mean?

2
  • use , instead of or
    – Tim
    Jul 9, 2018 at 15:03
  • right, can you tell for me about it
    – mducc
    Jul 9, 2018 at 15:04

1 Answer 1

21

You're using bitwise OR with or. This means that 1 or 7 evaluates to 7 and 4 or 10 evaluates to 14. 6 or 12 also happens to evaluate to 14, hence the compiler tells you it is a duplicate.

Solution: use , instead of or. See more on how to use when statements here.

2
  • I understand , vs or -- but why is "duplicate in when" a warning and not an error message? Seems like it's always a coding error.
    – pforhan
    Sep 10, 2018 at 13:01
  • @pforhan not sure, you would have to ask the kotlin team why they designed it to be a warning
    – Tim
    Sep 10, 2018 at 13:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.