Allow a property of a data class to only accept certain values

924 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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:

sealed class Flag {
    object A : Flag()
    object B : Flag()
}

or just throw in a require check in the init block with a list of valid constants, handle it at runtime!

1
On

probably by just defining it as an enum

enum view{
  GONE=0,
  VISIBLE=1,
  INVISIBLE=2,
}

class MyView{
  Public view visibility { get; set; }
}