Mpac
Mpac

Reputation: 931

Generic extending class with companion object in Kotlin

I write the following code but it doesn't works because I get an unresolved reference error.

class Chromosome {
    constructor() {}

    companion object {
        fun newInstance(): Chromosome {
            return Chromosome()
        }
    }
}

class Population<T>(size: Int) where T: Chromosome {
    var population: Array<T> = Array(size, { _ -> T.newInstance() })
}

I want a generic type T that extends a certain class or interface. I need to call a static factory methods because I cannot write T() in Array class constructor. Are there any way to wrap Array class calling a default constructor?

I tried with a different approach but it still not works. This time I get an Cannot use 'T' as reified type parameter. Use a class instead error.

class Population<T>(size: Int, init: () -> T) where T: Chromosome {
    var population: Array<T> = Array(size, { _ -> init() })
}

Upvotes: 2

Views: 2772

Answers (2)

tynn
tynn

Reputation: 39843

The Array type acts the same as the array in Java. Therefore it is special and does not work well with generics. Instead you should use a Java List approach. This means to use MutableList in Kotlin.

class Population<T: Chromosome>(size: Int, factory: () -> T) {
    var population = MutableList(size, { factory() })
}

Also be sure to implement Chromosome as open or abstract class. Otherwise you wouldn't need to make the population generic and the Array approach would work again.

Upvotes: 2

Jd Prajapati
Jd Prajapati

Reputation: 1971

You can try your Population class as code like below:

 class Population<T : Class<*>>(size: Int) where T: Chromosome {
...
}

Using above code your Population class can able to get the generic type of class.

I hope it helps you.

Upvotes: -1

Related Questions