IntDef and StringDef not being checked at compile time

While developing for Android we come across a lot of different annotation classes like IntDef and StringDef that effectively replace enums.

On Java that is no problem, as those annotations are checked in the compile time and we get suggestions and warnings based on that. Think of when you are setting the visibility of a view(in java) and the first suggestions are always INVISIBLE/GONE/VISIBLE, that is the power of IntDef. Programming for Kotlin? Then you always have to look up what is expected as input.

Now we can create the defs in Kotlin itself, which is great, but suggestions and warnings are still not there. Do we have some updates on that? am I missing something? Or what are your opinions on the subject?

3 Likes

This checking doesn’t come from the compiler, but from Android lint. Work to make android lint language independent is being done, but if I’m not mistaken you’ll need a newer version of Android Studio for it.

1 Like

That makes more sense, thanks for answering. I guess I will try to write my own Lint rules if anything is still missing after the update :slight_smile:

@raeglan I am trying to use @StringDef instead of Enum in my code.

@StringDef(TYPE_A , TYPE_B, TYPE_C)
@Retention(RetentionPolicy.SOURCE)
annotation class CodeResponse

and TYPE_A, TYPE_B and TYPE_C are defined in the companion object of outer class (not of class CodeResponse)

Is this the correct way to do it? also how to access these (TYPE_A, TYPE_B and TYPE_C) in a when expression

Hi @ggadkari, that is a bit of topic in this thread but I will give my opinion anyway.

If you have an outer class wrapping this CodeResponse and containing the companion object with your Long values called CodeResponses then just use CodeResponses.TYPE_A from inside a Kotlin file or CodeResponses.Companion.TYPE_A from a java class.

Cheers!

What Android Studio versions it is available in? I have the latest. I still can not see an error. it would be nice if you can point out what has to be done in order to have this working in Android Studio

Android Studio 4.1.2
Build #AI-201.8743.12.41.7042882, built on December 20, 2020
Runtime version: 1.8.0_242-release-1644-b3-6915495 x86_64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.16
GC: ParNew, ConcurrentMarkSweep
Memory: 3987M
Cores: 16
Registry: ide.new.welcome.screen.force=true, external.system.auto.import.disabled=true, ide.balloon.shadow.size=0
Non-Bundled Plugins: com.thoughtworks.gauge, org.intellij.plugins.markdown, com.intellij.marketplace, org.jetbrains.kotlin
4 Likes