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 thejava
is actually an invocation ofthis.java
which returns thejava.lang.Class
associated with theKClass
. Then theconstructors
gets an array ofConstructor
s from theClass
andsingle()
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).