Passing java class as parameter


#1

I’m trying to convert a portion of a java codebase to Kotlin. The core framework will still be java so I’m trying figure out how to call the java function from a Kotlin class.

The java interface for the function is:

Integer get(Class<? extends SomeInterface> clazz);

The way to call it in java would be:

input.get(SomeClass.class)

(SomeClass is an implementation of SomeInterface, both written in Java)

From Kotlin I would assume the call should look like

input.get(SomeClass::class)

but I am getting the error:

None of the following functions can be called with the arguments supplied.

  • get(Class<out SomeInterface!>! defined in...

Am I incorrectly passing the class as a parameter?

Side Note: when I copy and paste the java code into a kotlin class in intellij it autoconverts it to:

input.get(SomeClass::class.java)

but I get “unresolved reference: java”

Thank you.

pom contains:

    <dependency>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-stdlib</artifactId>
        <version>1.0.3</version>
    </dependency>
    <dependency>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-reflect</artifactId>
        <version>1.0.3</version>
    </dependency>

#2

SomeClass::class.java is correct. The “unresolved reference” error sounds like a dependency issue with the KClass.java extension property defined in kotlin-runtime not being found. Perhaps the IntelliJ project is not set up correctly? In Maven, you should be getting kotlin-runtime through kotlin-stdlib.


#3

https://kotlinlang.org/docs/reference/reflection.html

On the Java platform, the runtime component required for using the reflection features is distributed as a separate JAR file (kotlin-reflect.jar). This is done to reduce the required size of the runtime library for applications that do not use reflection features. If you do use reflection, please make sure that the .jar file is added to the classpath of your project.


#4

kotlin-reflect isn’t required for ::class.java.