What is java.constructors.single()?

99 views Asked by At

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?

1

There are 1 answers

0
Slaw On

It's important to realize you're in an extension function operating on an instance of KClass. So the java is actually an invocation of this.java which returns the java.lang.Class associated with the KClass. Then the constructors gets an array of Constructors from the Class and single() 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:

val clazz: java.lang.Class = this.java // 'this' is an instance of kotlin.reflect.KClass
val ctors: kotlin.Array<Constructor> = clazz.constructors
val ctor: java.lang.reflect.Constructor = ctors.single()

The single() function is an extension function defined on Array (and other types).