I'm learning Kotlin how to eval scripts, and I saw the code in BasicJvmScriptEvaluator like the following:
val ctor = java.constructors.single()
val saveClassLoader = Thread.currentThread().contextClassLoader
Thread.currentThread().contextClassLoader = this.java.classLoader
return try {
ctor.newInstance(*args.toArray())
} finally {
Thread.currentThread().contextClassLoader = saveClassLoader
}
I don't understand the code java.constructors.single(), there is no package named java.constructors. How should I understand this code?
It's important to realize you're in an extension function operating on an instance of
KClass. So thejavais actually an invocation ofthis.javawhich returns thejava.lang.Classassociated with theKClass. Then theconstructorsgets an array ofConstructors from theClassandsingle()gets the one (and only, else an exception is thrown) element in that array.If you expand the code into multiple lines it may be easier to see what's going on:
The
single()function is an extension function defined onArray(and other types).