Elye
Elye

Reputation: 60081

Java to Kotlin Array conversion, why different in different scenario?

Scenario 1 When I Dagger Modules Annotation as below from Java to Kotlin

@Module(includes = {AModule.class, XModule.class})

It changes to

@Module(includes = [AModule::class, XModule::class])

Scenario 2 However when I convert the below

Class<?>[] classArray = {AModule.class, XModule.class};

It changes to

val classArray = arrayOf(AModule::class.java, XModule::class.java)

Question Why does the conversion of {AModule.class, XModule.class} differ in the above 2 scenarios, where one is using [], and the other is using arrayOf instead?

Upvotes: 2

Views: 91

Answers (1)

s1m0nw1
s1m0nw1

Reputation: 81929

Since Kotlin 1.2, you can use array literals in annotations. These are not part of the actual Kotlin syntax and only reserved for annotations. This might change in the future but currently you cannot make use of array literals in your actual code.

Read about annotations here.

For other arguments that have an array type, you need to use the array literal syntax (since Kotlin 1.2) or arrayOf(...):

// Java

public @interface AnnWithArrayMethod {

    String[] names();

}

// Kotlin 1.2+:

@AnnWithArrayMethod(names = ["abc", "foo", "bar"]) 
class C

// Older Kotlin versions:

@AnnWithArrayMethod(names = arrayOf("abc", "foo", "bar")) 
class D

Upvotes: 3

Related Questions