starriet 차주녕
starriet 차주녕

Reputation: 3968

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

Upvotes: 5

Views: 227

Answers (1)

Sweeper
Sweeper

Reputation: 274480

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.

Upvotes: 5

Related Questions