Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you annotate Pair parameter in Kotlin?

Tags:

android

kotlin

I want to use Pair<Int, Int> as return type where one of the Int is annotated with @StringRes.

Pair<@param:StringRes Int, Int> gives deprecation warning.

like image 356
Ben Lewis Avatar asked Jun 07 '18 14:06

Ben Lewis


People also ask

How do you do annotations on Kotlin?

If you need to annotate the primary constructor of a class, you need to add the constructor keyword to the constructor declaration, and add the annotations before it: class Foo @Inject constructor(dependency: MyDependency) { ... }

How do I get data from Kotlin pairs?

The kotlin pair will return with any number of values and also it accepts more than one return value at a time. Using data class it returns the values from the functions and using pair and tuple class also using array values for possible to return the pair values in kotlin.

What is annotation processing Kotlin?

Annotation processing is a tool built into javac for scanning and processing annotations at compile time. It can create new source files; however, it can't modify existing ones. It's done in rounds. The first round starts when the compilation reaches the pre-compile phase.


2 Answers

As Lovis said, you can't do exactly that.

However if you want your signature to communicate that your parameter can't just be any Int but needs to be a @StringRes,@IdRes,@LayoutRes, etc., you could use typealiases as a workaround.

In my last project I had a file ResourceAnnotationAliases.kt that just defined this:

typealias StringRes = Int
typealias LayoutRes = Int
typealias IdRes = Int

So now you can give your Pair the signature Pair<StringRes, Int>.

Of course it will not show you an Error in the IDE when you input an Int that is not from R.string but at least your method signature will make clear what is expected.

like image 80
Daniel W. Avatar answered Sep 21 '22 20:09

Daniel W.


You can't. The problem is that Android's @StringRes is not applicable for the target TYPE_USE (or TYPE in Kotlin).

It would work if it was defined like this (java):

@Retention(SOURCE)
@Target({METHOD, PARAMETER, FIELD, TYPE_USE})
public @interface StringRes {
}

Now it would work:

fun fooIt(p: Pair<@StringRes Int, Foo>) {}

There is an open issue: https://issuetracker.google.com/issues/109714923

However, it might be possible that your solution actually works, despite of the deprecation warning. I haven't tested it.

like image 36
Lovis Avatar answered Sep 17 '22 20:09

Lovis