2

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?

1
  • 2
    Kotlin has no array literals for the normal program code. It is probably a design decision to use explicit function or constructor calls to create an array. In an annotation, function calls aren't allowed so this pseudo-literal notation is used. Commented Mar 21, 2019 at 1:20

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.