Ben Lewis
Ben Lewis

Reputation: 213

How do you annotate Pair parameter in 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.

Upvotes: 14

Views: 2924

Answers (2)

Daniel W.
Daniel W.

Reputation: 623

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.

Upvotes: 11

Lovis
Lovis

Reputation: 10057

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.

Upvotes: 10

Related Questions