Is there a way to use annotations to declare a return condition for kotlin functions?
For example, I want to tell lint that my function will return an Android resource id at:
fun getImageId(): Int
I would want something as:
fun getImageId(): @DrawableRes Int
which fails
I thought it would make sense (I believe is possible in Java), because I may have something as:
fun setImage(@DrawableRes res: Int) {
myImageView.setImageResource(res)
}
and call it as:
setImage(getImageId())
So that it has a chain of validations that the given int
is actually a Res Id
Kotlin function return values To return values, we use the return keyword. In the example, we have two square functions. When a funcion has a body enclosed by curly brackets, it returns a value using the return keyword. The return keyword is not used for functions with expression bodies.
I know unit is the default return type in kotlin.
By prefixing the annotation with @get: the resulting bytecode will have the annotation on the generated getter function: // Decompiled from the resulting Kotlin Bytecode @SomeAnnotation @Nullable public final String getSomeProperty() { return this. someProperty; }
In Java, an annotation type is a form of an interface, so you can implement it and use an instance. As an alternative to this mechanism, Kotlin lets you call a constructor of an annotation class in arbitrary code and similarly use the resulting instance.
We can annotate the properties of class by adding an annotation to the properties. In below example, we assume that an Lang instance is valid if the value of the name is either Kotlin or Java. Kotlin also provides certain in-built annotations, that are used to provide more attributes to user-defined annotations.
Kotlin does not infer return types for functions with block bodies because such functions may have complex control flow in the body, and the return type will be non-obvious to the reader (and sometimes even for the compiler). You can mark a parameter of a function (usually the last one) with the vararg modifier: Copied!
UPD. There is alternative implementation that uses a bit of kotlin magic, specifically, reified types. With this approach instead of having separate entities to define the field that you want to be returned from getOffer function you just specify explicit type parameter. Alternatively you can rely on implicit type inference:
Moreover, we can use arrays and collections to return up to five values of the same type: The Kotlin limit is five because it has defined five componentN extension functions on arrays and collections. Sometimes, it’s better to define a custom type with a meaningful name.
You can do it with:
@DrawableRes
fun getImageId(): Int
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With