Support mapping between Kotlin functions and JVM methods/constructors

This commit is contained in:
Alexander Udalov
2015-07-15 23:33:37 +03:00
parent 93656c93c1
commit 936bede8b1
14 changed files with 323 additions and 38 deletions
@@ -0,0 +1,7 @@
public class javaConstructor {
public final String result;
public javaConstructor(String result) {
this.result = result;
}
}
@@ -0,0 +1,12 @@
import kotlin.reflect.*
import kotlin.reflect.jvm.*
import javaConstructor as J
fun box(): String {
val reference = ::J
val javaConstructor = reference.javaConstructor ?: return "Fail: no Constructor for reference"
val j = javaConstructor.newInstance("OK")
val kotlinConstructor = javaConstructor.kotlinFunction
if (reference != kotlinConstructor) return "Fail: reference != kotlinConstructor"
return j.result
}
@@ -0,0 +1,9 @@
public class javaMethods {
public String f(String s) {
return s;
}
public static String g(String s) {
return s;
}
}
@@ -0,0 +1,19 @@
import kotlin.reflect.*
import kotlin.reflect.jvm.*
import javaMethods as J
fun box(): String {
val f = J::f
val fm = f.javaMethod ?: return "Fail: no Method for f"
if (fm.invoke(J(), "abc") != "abc") return "Fail fm"
val ff = fm.kotlinFunction ?: return "Fail: no KFunction for fm"
if (f != ff) return "Fail f != ff"
val g = J::g
val gm = g.javaMethod ?: return "Fail: no Method for g"
if (gm.invoke(null, "ghi") != "ghi") return "Fail gm"
val gg = gm.kotlinFunction ?: return "Fail: no KFunction for gm"
if (g != gg) return "Fail g != gg"
return "OK"
}
@@ -0,0 +1,35 @@
import kotlin.reflect.*
import kotlin.reflect.jvm.*
class K {
class Nested
inner class Inner
}
class Secondary {
constructor(x: Int) {}
}
fun check(f: KFunction<*>) {
assert(f.javaMethod == null, "Fail f method")
assert(f.javaConstructor != null, "Fail f constructor")
val c = f.javaConstructor!!
assert(c.kotlinFunction != null, "Fail m function")
val ff = c.kotlinFunction!!
assert(f == ff, "Fail f != ff")
}
fun box(): String {
check(::K)
// Workaround KT-8596
val nested = K::Nested
check(nested)
check(K::Inner)
check(::Secondary)
return "OK"
}
@@ -0,0 +1,27 @@
import kotlin.reflect.*
import kotlin.reflect.jvm.*
class K {
fun foo(s: String): Int = s.length()
}
fun bar(s: String): Int = s.length()
fun String.baz(): Int = this.length()
fun check(f: KFunction<Int>) {
assert(f.javaConstructor == null, "Fail f constructor")
assert(f.javaMethod != null, "Fail f method")
val m = f.javaMethod!!
assert(m.kotlinFunction != null, "Fail m function")
val ff = m.kotlinFunction!!
assert(f == ff, "Fail f != ff")
}
fun box(): String {
check(K::foo)
check(::bar)
check(String::baz)
return "OK"
}