0

I saw some examples of extension functions being defined inside a class/interface but I didn't understand the reason it would be done. Could someone show when it would be the proper way to implement some use case?

One particular example that I didn't understand very well:

interface Monoid<A> { 
    fun z(): A 
    fun A.add(other:A):A 
}
Diego Marin Santos
  • 1,923
  • 2
  • 15
  • 29
  • Remember that extension functions are just regular functions with slightly altered call syntax (receiver is basically first argument). Personally I only create private inner extensions to prevent confusion. – Pawel Nov 27 '19 at 23:14

1 Answers1

0

When you only ever want to use this function inside your class/interface and its subtypes (or nearly so; you already know how to get out with with as per your previous question, but that shouldn't be a common case).

The specific example just seems like a bad idea once you need to work with more than one Monoid at once.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487