Search code examples
javaandroidkotlindagger

is 'ClassName.class' in Java same as '[ClassName::class]' in Kotlin?


On the Android dev page, in the Dagger section,

NetworkModule.class in Java code is written as [NetworkModule::class] in Kotlin code.

  1. I thought NetworkModule.class in Java should be NetworkModule::class.java in Kotlin, isn't it?

  2. why use the square brackets([])? I think it's the same as get, but why do we need it?

I was reading this: https://developer.android.com/training/dependency-injection/dagger-android#java

In the 'Dagger Modules' section,

Java code:

@Component(modules = NetworkModule.class)
public interface ApplicationComponent {
    ...
}

the same code written in Kotlin:

@Component(modules = [NetworkModule::class])
interface ApplicationComponent {
    ...
}

Solution

  • This is the array literal syntax supported only in annotations, added in Kotlin 1.2. You can use it to pass arrays of things to annotations. So [NetworkModule::class] is actually an array containing a single element, that being NetworkModule::class.

    The Kotlin code translated to Java would be:

    @Component(modules = { NetworkModule.class })
    interface ApplicationComponent {
        ...
    }
    

    It's just that the {} brackets can be omitted in Java, when there is a single element in the array. However, you can't just write NetworkModule::class in Kotlin. You have to explicitly say that it's an array, using ways such as [], or arrayOf, unless it's the value parameter, in which case it is translated as vararg.

    In general, NetworkModule.class in Java should be translated to NetworkModule::class when in an annotation. But note that this is of type KClass. If you want a java.lang.Class, add .java.