What is “duplicate in when” in Kotlin?

  • A+
Category:Languages

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?

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: