Why methodHandle can't work in kotlin


#1

The same code run succeed in java,then I translateto kotlin version and get a WrongMethodTypeException.
here’s the code

    class Test {
        companion object{
            @JvmStatic fun main(array: Array<String>) {
                val t=Test()
                val methodType=MethodType.methodType(Int::class.java,Int::class.java,Int::class.java)
                val methodHandle= MethodHandles.publicLookup().findVirtual(t.javaClass,"add",methodType)
                val result= methodHandle.invoke(t,3,5)
                println(result)
            }
        }

        fun add(a:Int,b:Int):Int{
            return a+b
        }
    }

Thanks


Is MethodHandle support coming? (When is Java 8 support expected?)
#2

Int::class.java corresponds to java.lang.Integer, while the parameters of the add method have the type int. To get the Java class for the int type, use Int::class.javaPrimitiveType.


#3

Monkey,

As you surely discovered, switching to using javaPrimitiveType still isn’t enough for your code to actually work in Kotlin. If Kotlin still interests you, you should vote on this Kotlin issue and hope it gets fixed.