Some context first. In Android using Kotlin, changing the visibility is done like in the following.
myView.visibility = View.VISIBLE
Setting any other Int
value other than View.VISIBLE
, View.INVISIBLE
or View.GONE
returns an error.
Now I have a Kotlin data class that accepts a constructor parameter flag
of type Int
.
How do I implement this the same way in my Kotlin code such that myClass.flag = Flag.A
and no other value?
If you want the same warning behaviour as you get for
View.visibility
constants, you'll need to write a lint check for it. Here's a couple of blogs about doing that sort of thing:https://www.bignerdranch.com/blog/building-custom-lint-checks-in-android/
https://medium.com/@vanniktech/writing-your-first-lint-check-39ad0e90b9e6
If you want to enforce a type, then like people have said enums are a way to go, or you could use a sealed class:
or just throw in a
require
check in theinit
block with a list of valid constants, handle it at runtime!