title: AOP with Kotlin
body: <p>I used AOP a lot with Java. It looks like that traditional java approaches can easily be reused with Kotlin. Given Kotlin emphasis on immutability JDK proxies seem to be the most feasible solution in Kotlin provided that you're following the same interface-first (better say trait-first in Kotlin) programming style, e.g.:</p>
  
  <pre><code>trait MyService {
   fun add(a: Int, b: Int): Int
  }
  
  class MyServiceImpl: MyService {...}
  </code></pre>
  
  <p>So now one can easily write an aspect in, say, Spring/AOP and apply it to the instances of MyServiceImpl. It should be mentioned that Java interface-based generated proxies may be more favored by Kotlin developers as cglib requires to get rid of final (i.e. resort to open classes in Kotlin) and use parameterless public constructors for every class which should be wrapped by AOP proxies.</p>
  
  <p>At the same time Java interface-based generated proxies unfortunately impose significant performance penalty so I'm wondering if AOP programming can be done more intuitively or natively to Kotlin in some cases.</p>
  
  <p>So, consider the following example, when I want to use AOP for:</p>
  
  <ul>
  <li>Logging arguments and return result of each method exposed from a service.</li>
  <li>Starting transaction before function call and closing it after function call completes (commit/rollback depending on whether or not an exception has been thrown while making a particular service call).</li>
  </ul>
  
  <p>The most effective but unfortunately the most verbose brute-force solution in the aforementioned example with MyService/MyServiceImpl might look as follows:</p>
  
  <pre><code>class MyServiceLoggingWrapper(val delegate: MyService): MyService {
    val logger = LoggerFactory.getLogger(this.javaClass)
  
    override fun add(a: Int, b: Int): Int {
      val result = delegate.add(a, b);
      logger.info("MyService.add({}, {}) = {}", a, b, result);
      return result;
    }
  } 
  
  class MyServiceTxWrapper(val delegate: MyService, val txManager: TransactionManager): MyService {
   // similar lengthy implementation
  }
  </code></pre>
  
  <p>The LoC complexity of that approach is O(N*K) where N is a number of method and K is a number of aspects that I want to apply.</p>
  
  <p>So what I'm looking is a possible effective (both in terms of performance and LoC) solution for aspects in Kotlin preferrably without resorting to cglib-generated proxies as they impose too many limitations like saying goodbye to final classes and not having parameterless public constructors.</p>