2

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() }) } 
3
  • I think ClassY is Class Y. Right? Commented Oct 30, 2017 at 15:11
  • This is as problematic in Java as in Kotlin. How would you implement this exactly in Java? Commented Oct 30, 2017 at 15:15
  • @tynn Good question. I tried to implement in Java but it doesn't work too. So you are right when you say that this is problematic in both languages. Commented Oct 30, 2017 at 16:36

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

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.

1 Comment

Thank you for your suggestion but it doesn't work. I get these errors: Upper bounds of T have empty intersection and Only one of the upper bounds can be a class.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.