I'm writing it down here, because I looked at it and didn't understand what was going on.
The "by" keyword in Kotlin is used for two things:
- Interface/Class delegation1
- Delegated properties2
Delegation is a good alternative to inheritance (thought this last statement really requires explanation, or a blogpost on it's own,... or, dare I say, a study on when to use inheritance and when to use delegation and when to use the good old composition).
With the "by" keyword it is possible to use delegation, without adding to the amount of boilerplate that this entails and without having to use inheritance.
Let us give an example using Stubs in testing.
Stubs
So, it seems it's possible to create a simple stub for a test, by using an interface and an implementation and overriding a method (for stubbing). Naturally, the method is not "overridden", but using delegation it is simply implemented in the test, and all other methods are redirected to the stub (which is the delegation class).
So, the syntax1 looks like this:
So, for example if you wish to use a delegation (instead of inheritance) in your stub for an OrderService interface.
You create a OrderServiceStub, which makes an empty implementation of all the methods in de OrderService.
And then you can create an anonymous class, indicating which method you wish to change to benefit the test.
It looks like this:
Notice that the anonymous inner class does not inherit from OrderServiceStub (in Kotlin classes are final by default, and we'd like to keep it that way).
The way this can be done without boilerplace in Kotlin is as follows:
So in the second test we're creating an anonymous class, which implements the interface automatically by delegating to the Stub. The only thing we need to change is the method we're interested in.
The next blogpost, we will be diving deeper into Delegated Properties, which looks a little more complicated but is based on the same ideas.
References
- [1] Kotlin Language Reference - Delegation
- https://kotlinlang.org/docs/delegation.html
- [2] Kotlin Language Reference - Delegated properties
- https://kotlinlang.org/docs/delegated-properties.html
- [3] StackOverflow - What does 'by' keyword do in Kotlin?
- https://stackoverflow.com/questions/38250022/what-does-by-keyword-do-in-kotlin