# Declare member extensions outside the class

**URL:** <https://discuss.kotlinlang.org/t/declare-member-extensions-outside-the-class/6759>\
**Category:** Language Design\
**Created:** [February 23, 2018, 2:01pm UTC](https://discuss.kotlinlang.org/t/declare-member-extensions-outside-the-class/6759 "2018-02-23T14:01:35Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![darksnake](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/darksnake/32/2479_2.png) [@darksnake](https://discuss.kotlinlang.org/u/darksnake)\
**Post date:** [February 23, 2018, 2:01pm UTC](https://discuss.kotlinlang.org/t/declare-member-extensions-outside-the-class/6759/1 "2018-02-23T14:01:35Z")

</div>

Extensions are the brilliant invention of the Kotlin team and I use them a lot. [Member extensions](https://kotlinlang.org/docs/reference/extensions.html#declaring-extensions-as-members) are very useful do declare convenience methods and us create DSL and other utility constructs in case one needs to limit some behavior only when a specific class used as a receiver.

Lately I’ve encountered a multiple cases, when I want to declare a member extension to already existing classes. For example, I have some kind of mathematical context and want to declare arithmetic operations on numbers like:

```kotlin
class ContextClass{
  operator fun Number.plus(n: Number): Number{
    ...
  }
}

```

Another example is when I need to generate a synthetic property for an object but only when it is used as argument of some method in another class.

It could be done easily in kotlin if we are talking about user-defined classes written in kotlin. But It seems to be impossible for java classes or for library classes. From my naive point of view it should be possible to add those member extensions from outside of context class, but Kotlin currently lacks syntax for that.

So my question is: is it done by design and is it possible to add such syntax?

---

<div class="post-metadata">

**Author:** ![tieskedh](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/tieskedh/32/2816_2.png) [@tieskedh](https://discuss.kotlinlang.org/u/tieskedh)\
**Post date:** [February 23, 2018, 9:24pm UTC](https://discuss.kotlinlang.org/t/declare-member-extensions-outside-the-class/6759/2 "2018-02-23T21:24:15Z")

</div>

As an extension-function with multiple receivers:

a post from 2014

> [@Extension functions inside class](https://discuss.kotlinlang.org/t/extension-functions-inside-class/515/4):
>
> No, multiple receivers are not supported at the moment. We have this in our backlog, but it's hard to say when we'll get to it. We are also aware of the issue of limiting the scope of extensions (like String.plus) for DSL purposes. We have some ideas about it, but no final decision.

and from 2017:

> [@Extension Function/Property with two receivers](https://discuss.kotlinlang.org/t/extension-function-property-with-two-receivers/2188/3):
>
> We’ve seen several usecases where such properties could be needed, but so far we’re trying to avoid adding them to the language. Single-receiver extension properties can be hard enough to explain, and this becomes even less obvious. Note that your scenario can be partially solved with a member extension property defined in a base class that all of your activities extend.

So, it wasn’t by design, but I’m not hopefull…

But, maybe it will be possible as inline class?

---

<div class="post-metadata">

**Author:** ![darksnake](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/darksnake/32/2479_2.png) [@darksnake](https://discuss.kotlinlang.org/u/darksnake)\
**Post date:** [February 24, 2018, 5:12am UTC](https://discuss.kotlinlang.org/t/declare-member-extensions-outside-the-class/6759/3 "2018-02-24T05:12:07Z")

</div>

Thanks, missed that post because of different wording.

So the problem is purely syntactic A agree, that `fun A.B.method()` looks a bit confusing (not drastically though), but maybe there could be another solution. Something with `with` maybe?

---

<div class="post-metadata">

**Author:** ![fvasco](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/fvasco/32/1961_2.png) [@fvasco](https://discuss.kotlinlang.org/u/fvasco)\
**Post date:** [February 24, 2018, 7:30am UTC](https://discuss.kotlinlang.org/t/declare-member-extensions-outside-the-class/6759/4 "2018-02-24T07:30:12Z")

</div>

Want you define your algebra?

```auto
object ContextClass{
  operator fun Number.plus(n: Number): Number{
    ...
  }
}

with (ClassContext) {
    val sum = number1 + number2
}

```

I wrote a long post about this (and more) here

> <https://github.com/Kotlin/KEEP/pull/87#issuecomment-366989987>
>
> \## Proposal
> 
> The goal of this proposal is to enable compile-time dependency re…solution through extension syntax. Overall, we want to enable "contract" interfaces to be declared as program constraints in function or class constructor arguments and enable the compiler to automatically resolve and inject those instances that must be provided with evidence in one of a given set of scopes. The resolution scopes to look for those evidences are predefined and ordered, \[more details inside the proposal\](https://github.com/Kotlin/KEEP/pull/87/files). 
> 
> In the case of not having evidence of a required interface (program constraints), the compiler would fail and provide the proper error messages both by IntellIJ IDEA inspections and compile-time errors.
> 
> This would bring first-class named extension families to Kotlin. Extension families allow us to guarantee that a given data type (class, interface, etc.) satisfies behaviors (a group of functions or properties) that are decoupled from the type's inheritance hierarchy. 
> 
> Unlike the traditional subtype style composition where users are forced to extend and implement classes and interfaces, extension families favor horizontal composition based on compile-time resolution between types and their extensions.
> 
> \## Current code status
> 
> Thanks to @truizlop and @jorgecastilloprz,\[we already have a working POC\](https://github.com/arrow-kt/kotlin/pull/6) where we've coded a big part of the KEEP-87. There are still some additional behaviors we'd need to code that have been clarified on the KEEP though, and we'd love to get JetBrains help on iterating those. Instructions about how to test it have been provided within the \["How to try?"\](https://github.com/Kotlin/KEEP/pull/87/files#diff-71ce63753e7dbd24fcb8b631141583ccR431) section of the keep, where we have also provided a code sample.
> 
> \## Rewording
> 
> We have revamped the initial proposal given Type Classes are not really our aim here, but compile-time dependency resolution for Kotlin. The nature of the proposal has not changed a lot, just suffered a major refactor so it's more in the line of what a generic language feature like this one would be, and also to fit the compiler implementation feedback we've got from some JetBrains devs these later months. 
> 
> We believe the compiler could support compile-time dependency resolution out of the box, as other modern laguages already do. We believe some infrastructure patterns would fit better as built-in language features, so users can get their canonical solution for that already provided and focus their work on the actual domain requirements and business logics of their programs. We've seen similar things in other languages that provide built in support for concurrency and other stuff.
> 
> \## How to contribute
> 
> Want to help to bring compile time extension resolution to Kotlin?. A fork is being provisioned where a reference implementation based on this proposal will take place at https://github.com/arrow-kt/kotlin

Here how to defien a Ring using the typeclass, but this can be easy translated to Kotlin 1.2

> <https://github.com/Kotlin/KEEP/pull/87#issuecomment-366705095>
>
> \## Proposal
> 
> The goal of this proposal is to enable compile-time dependency re…solution through extension syntax. Overall, we want to enable "contract" interfaces to be declared as program constraints in function or class constructor arguments and enable the compiler to automatically resolve and inject those instances that must be provided with evidence in one of a given set of scopes. The resolution scopes to look for those evidences are predefined and ordered, \[more details inside the proposal\](https://github.com/Kotlin/KEEP/pull/87/files). 
> 
> In the case of not having evidence of a required interface (program constraints), the compiler would fail and provide the proper error messages both by IntellIJ IDEA inspections and compile-time errors.
> 
> This would bring first-class named extension families to Kotlin. Extension families allow us to guarantee that a given data type (class, interface, etc.) satisfies behaviors (a group of functions or properties) that are decoupled from the type's inheritance hierarchy. 
> 
> Unlike the traditional subtype style composition where users are forced to extend and implement classes and interfaces, extension families favor horizontal composition based on compile-time resolution between types and their extensions.
> 
> \## Current code status
> 
> Thanks to @truizlop and @jorgecastilloprz,\[we already have a working POC\](https://github.com/arrow-kt/kotlin/pull/6) where we've coded a big part of the KEEP-87. There are still some additional behaviors we'd need to code that have been clarified on the KEEP though, and we'd love to get JetBrains help on iterating those. Instructions about how to test it have been provided within the \["How to try?"\](https://github.com/Kotlin/KEEP/pull/87/files#diff-71ce63753e7dbd24fcb8b631141583ccR431) section of the keep, where we have also provided a code sample.
> 
> \## Rewording
> 
> We have revamped the initial proposal given Type Classes are not really our aim here, but compile-time dependency resolution for Kotlin. The nature of the proposal has not changed a lot, just suffered a major refactor so it's more in the line of what a generic language feature like this one would be, and also to fit the compiler implementation feedback we've got from some JetBrains devs these later months. 
> 
> We believe the compiler could support compile-time dependency resolution out of the box, as other modern laguages already do. We believe some infrastructure patterns would fit better as built-in language features, so users can get their canonical solution for that already provided and focus their work on the actual domain requirements and business logics of their programs. We've seen similar things in other languages that provide built in support for concurrency and other stuff.
> 
> \## How to contribute
> 
> Want to help to bring compile time extension resolution to Kotlin?. A fork is being provisioned where a reference implementation based on this proposal will take place at https://github.com/arrow-kt/kotlin

I hope this may help you.

---

<div class="post-metadata">

**Author:** ![darksnake](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/darksnake/32/2479_2.png) [@darksnake](https://discuss.kotlinlang.org/u/darksnake)\
**Post date:** [February 24, 2018, 8:06am UTC](https://discuss.kotlinlang.org/t/declare-member-extensions-outside-the-class/6759/5 "2018-02-24T08:06:48Z")

</div>

Type classes (while being very interesting idea) are a bit of overkill for the thing I am asking about, since member extension are already in the language, and it should be easy to declare them outside of class scope.The only thing which is not there is a syntax to declare receiver hierarchy.

As for implementation, I’ve already implemented it [here](https://bitbucket.org/Altavir/dataforge/src/a6b874919007b785bd75091bd88ba3061b033ee3/dataforge-maths/src/main/kotlin/hep/dataforge/maths/expressions/Field.kt?at=ad&fileviewer=file-view-default) and [here](https://bitbucket.org/Altavir/dataforge/src/a6b874919007b785bd75091bd88ba3061b033ee3/dataforge-maths/src/main/kotlin/hep/dataforge/maths/expressions/DSNumber.kt?at=ad&fileviewer=file-view-default) with resulting code example [here](https://bitbucket.org/Altavir/dataforge/src/a6b874919007b785bd75091bd88ba3061b033ee3/dataforge-maths/src/test/java/hep/dataforge/maths/expressions/DSFieldTest.kt?at=ad&fileviewer=file-view-default). It works just fine in kotlin, and I probably would not be able to implement it using member extensions anyway, since I had to add additional field to context class anyway. The only problem arises in case one wants to use existing Java class as a context.

I promised commons-math guys to back port kotlin solution to java, so in the end I will have to use java classes if I do not want to keep two implementations of the same thing.

---

<div class="post-metadata">

**Author:** ![moomoon](https://avatars.discourse-cdn.com/v4/letter/m/858c86/32.png) [@moomoon](https://discuss.kotlinlang.org/u/moomoon)\
**Post date:** [February 24, 2018, 9:32am UTC](https://discuss.kotlinlang.org/t/declare-member-extensions-outside-the-class/6759/6 "2018-02-24T09:32:20Z")

</div>

Maybe you could try something like this:

```kotlin
object ContextClass
object Number

val ContextClass.plus: Number.(Number) -> Number get() = { TODO() }
val result = ContextClass.run {
  Number.plus(Number)
}

```

But it seems that the `operator` keyword won’t work though.

---

<div class="post-metadata">

**Author:** ![darksnake](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/darksnake/32/2479_2.png) [@darksnake](https://discuss.kotlinlang.org/u/darksnake)\
**Post date:** [February 24, 2018, 10:09am UTC](https://discuss.kotlinlang.org/t/declare-member-extensions-outside-the-class/6759/7 "2018-02-24T10:09:00Z")

</div>

An interesting idea (not for my case, but for global multi-receiver problem). But still, it looks like a workaround, not a good solution.

Creating a wrapper class, which delegates methods to internal implementation looks better.

---

<div class="post-metadata">

**Author:** ![fvasco](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/fvasco/32/1961_2.png) [@fvasco](https://discuss.kotlinlang.org/u/fvasco)\
**Post date:** [February 24, 2018, 10:26am UTC](https://discuss.kotlinlang.org/t/declare-member-extensions-outside-the-class/6759/8 "2018-02-24T10:26:13Z")

</div>

Your solution looks good,  
What is your issue about it?

---

<div class="post-metadata">

**Author:** ![darksnake](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/darksnake/32/2479_2.png) [@darksnake](https://discuss.kotlinlang.org/u/darksnake)\
**Post date:** [February 24, 2018, 11:44am UTC](https://discuss.kotlinlang.org/t/declare-member-extensions-outside-the-class/6759/9 "2018-02-24T11:44:55Z")

</div>

No problem here, it works. It is just that I recently noticed a few places, where I would like to add member extensions to Java classes. Overall, this request in just a syntactic sugar, but the idea looks so good…
