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.
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) { ... }
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.
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.
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.
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.
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