Add extension method to global scope

Hey there! I am trying to create a Gradle-esque ScriptingInterface for my small toy application. I came up with following method:

    fun <T>addExtension(name: String, type: Class<T>): T {
    operator fun T.invoke(cls: T.() -> Unit) {

    val instance = type.getConstructor().newInstance()
    scriptEngine.put(name, instance)

    return instance

When I execute following script:

product {
    name = "Hello, World!"

The execution fails with following extension:

javax.script.ScriptException: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public operator fun <T, R> DeepRecursiveFunction<TypeVariable(T), TypeVariable( R)>.invoke(value: TypeVariable(T)): TypeVariable( R) defined in kotlin

However, when I add the operator to the class itself, i.e. like this:

open class Robot {
    var name: String = ""        
    operator fun invoke(init: Product.() -> Unit) {

instead of creating the extension inside a method, then everything works fine and dandy. My guess is, that the extension is only accessible within the scope of the method that creates it.

I am quite new to Kotlin (or the whole JVM Ecosystem). Is there any way I can circumvent this obstacle?

Yes this is by design.

If you want something to be global you define it at global space.

operator fun <T> T.invoke(cls: T.() -> Unit) {