Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Integer.class from Kotlin

Tags:

kotlin

I have a Java method that accepts Class parameter. I need to pass Integer.class to it, but from Kotlin code. I tried Int::class.java, however this does not work, because int.class is passed to the function. My question is, how do I access Integer.class from Kotlin.

Java

void foo(Class clazz);

Kotlin

foo(Int::class.java) // does not work, int.class gets passed to foo
like image 893
rozina Avatar asked Aug 11 '17 10:08

rozina


People also ask

How do I get int with Kotlin?

To convert a string to integer in Kotlin, use String. toInt() or Integer. parseInt() method. If the string can be converted to a valid integer, either of the methods returns int value.

What is the difference between int and Integer in Kotlin?

[Int] Represents a 32-bit signed integer. On the JVM, non-nullable values of this type are represented as values of the primitive type int. Integer is a Java Class. If you were to search the Kotlin spec for "Integer", there is no Kotlin Integer type.


1 Answers

You must use the KClass#javaObjectType to get the wrapper type class in Kotlin:

Returns a Java Class instance corresponding to the given KClass instance. In case of primitive types it returns corresponding wrapper classes.

For example:

//                  v--- java.lang.Integer
println(Int::class.javaObjectType)

//                  v--- int
println(Int::class.java)
like image 102
holi-java Avatar answered Sep 18 '22 08:09

holi-java