I am messing around with dl4j in Kotlin and trying to build a generic function. Basically I want to take functions like these:
fun NeuralNetConfiguration.ListBuilder.dense(init: DenseLayer.Builder.() -> Unit) {
this.layer(DenseLayer.Builder().apply(init).build())
}
fun NeuralNetConfiguration.ListBuilder.conv2d(init: ConvolutionLayer.Builder.() -> Unit) {
this.layer(ConvolutionLayer.Builder().apply(init).build())
}
and generalize them to a function:
fun <T> buildLayer(parent: NeuralNetConfiguration.ListBuilder, init: Layer<T>.Builder.() -> Unit) {
parent.layer(Layer<T>.Builder().apply(init).build())
}
This generic function should take a NeuralNetConfiguration.ListBuilder
object and apply the function init. In the extension functions I want to use buildLayer
like this:
fun NeuralNetConfiguration.ListBuilder.dense(init: DenseLayer.Builder.() -> Unit) {
buildLayer<DenseLayer>(this, init)
}
fun NeuralNetConfiguration.ListBuilder.conv2d(init: ConvolutionLayer.Builder.() -> Unit) {
buildLayer<ConvolutionLayer>(this, init)
}
Unfortunately I am stuck with the proper generic typing. The compiler throws two errors:
- for the Builder of init in the signature: One type argument expected for class Builder<T : Layer.Builder<T!>!>
- for the Layer in the body: Cannot create an instance of an abstract class
Im am new to Kotlin and my last time writing Java was too long ago. Following the IDE hints took me nowhere. Does anyone know how to get the generic typing right?
Thanks in advance.