The problem arises from the fact that Kotlin class delegation allows to delegate only to constructor parameters, thus seemingly forcing you to provide constructor with an argument.
Below is my original question pertaining to a concrete use case of this problem.
I want to do the following:
val myTable1: MyTable = MyTable()
where
MyTable
inherits from ImmutableTable (src) or at least Table Table
methods to some base implementation.I also want to avoid the following:
val myTable2: MyTable = MyTable.build()
i.e. I do not want to be forced to use companion objects / static factory methods.
I tried to extend ImmutableTable
, but I am getting This type has a constructor, and thus must be initialized here
.
I tried to extend Table
interface and delegate to it (to avoid reimplementing methods) but then I am forced to provide an instance of Table
as constructor parameter. I cannot just initialize it in init {}
block.
Please see this gist for my exact attempts.
Kotlin version used: 1.0.2
Delegation is used in Kotlin with the help of “by” keyword. • Explicit delegation: Supported by all object-oriented language and it is done by passing a delegate (the one to be implemented) object to delegating object (the one that will implement delegate object). • Implicit delegation: Requires language-level support for the delegation pattern.
Interfaces in Kotlin can contain declarations of abstract methods, as well as method implementations. What makes them different from abstract classes is that interfaces cannot store state. They can have properties but these need to be abstract or to provide accessor implementations. An interface is defined using the keyword interface
• Implicit delegation: Requires language-level support for the delegation pattern. As we know that in Kotlin, inheritance provides us with a permanent static relationship between objects which are not mutable while delegation is, this fact makes Delegation an extremely powerful alternative.
Kotlin provides native capabilities to implement the delegation pattern without the need to write any boilerplate code. This is only working on interfaces (in other words abstract classes). The interface implementation of IWalking is done as shown in the following code.
As mentioned in comments, Guava has ForwardingTable
that can accomplish this. But here's another option that should work even for interfaces where there isn't a "forwarding" version defined.
class MyTable private constructor(table: Table<Int, Int, Int>) : Table<Int, Int, Int> by table {
constructor() : this(TreeBasedTable.create()) // or a different type of table if desired
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With