# Add extension method to global scope

**URL:** https://discuss.kotlinlang.org/t/add-extension-method-to-global-scope/21121
**Category:** Support
**Created:** [March 7, 2021, 8:14pm UTC](https://discuss.kotlinlang.org/t/add-extension-method-to-global-scope/21121 "2021-03-07T20:14:23Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![HiImJulien](https://avatars.discourse-cdn.com/v4/letter/h/ce7236/32.png) [@HiImJulien](https://discuss.kotlinlang.org/u/HiImJulien)
#### Post date: [March 7, 2021, 8:14pm UTC](https://discuss.kotlinlang.org/t/add-extension-method-to-global-scope/21121/1 "2021-03-07T20:14:23Z")

</div>

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) {
        cls(this)
    }

    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) {
        init(this)
    }
}

```

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?

---

<div class="post-metadata">

### Author: ![al3c](https://avatars.discourse-cdn.com/v4/letter/a/e47774/32.png) [@al3c](https://discuss.kotlinlang.org/u/al3c)
#### Post date: [March 8, 2021, 1:43pm UTC](https://discuss.kotlinlang.org/t/add-extension-method-to-global-scope/21121/2 "2021-03-08T13:43:30Z")

</div>

> [@HiImJulien](#):
>
> 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.

Yes this is by design.

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

```kotlin
operator fun <T> T.invoke(cls: T.() -> Unit) {
    cls(this)
}

```
