KEEP icon indicating copy to clipboard operation
KEEP copied to clipboard

Types as annotation arguments

Open abreslav opened this issue 9 years ago • 2 comments

Currently, we can only mention classes in annotation arguments: @Ann(Foo::class). Although in some contexts terms class and type can be used interchangeably, those are two different things, for example, a class Foo can be mentioned in many different types: Foo, Foo<Bar>, Foo<Foo<Bar>>, Foo<*>, `Bar<Foo>, etc.

Sometimes we need to refer to types, not classes. For example, in many cases it's useless to say List::class, we need more information like List<String> or List<Nothing>.

We propose adding support for types as annotation arguments (and, optionally, elsewhere in the language):

  • an annotation parameter may be declared to be of type KType,
  • an annotation argument may be a type (in some syntactic form, e.g. @Ann(Foo<Bar>)).

Example (syntax is subject to discussion):

annotation class Ann(val type: KType)

@Ann(type = Foo<Bar>)
fun test() {} 

This is relevant for #38

abreslav avatar Jul 25 '16 12:07 abreslav

How would this be represented in Java?

This might also be a good opportunity to bring up built-in type literals for the rest of the language, to replace the java-style hacks like TypeLiteral and TypeToken. I'd think that if I can represent a type literal in an annotation, I should be able to do so in code as well.

val listOfStringType = List<String>::type

damianw avatar Sep 29 '16 23:09 damianw

How would this be represented in Java?

We have two options:

  • represent such types as strings, e.g. "Foo<Bar>"
  • represent them as annotations, e.g. @Ann(type = @Type(name = "Foo", args = {@Type(name = "Bar)})`

This might also be a good opportunity to bring up built-in type literals for the rest of the language

Fair point.

abreslav avatar Sep 30 '16 15:09 abreslav