colymore
colymore

Reputation: 12346

How to avoid kotlin factory class method by subtype?

i have a question about kotlin:

Imagine you have this:

sealed class Graph : Serializable
data class Graph1() : Graph() {}
data class Graph2() : Graph() {}

And you want to have a factory class that given a subtype of Graph gives you a GraphView.

So, you have something similar to

interface GraphViewFactory{
  fun get(data: Graph1):GraphView
  fun get(data: Graph2):GraphView
}

And also you have the implementation for that.

Is possible in kotlin avoid this method explosion of interface having one per graphtype using inline and reified? I'm trying to but i'm not being able.

On the one hand, kotlin interface (I think) does not allow inline functions, on the other hand even without the interface i'm not able to auto cast parameter T as reified to one of the specific subtype class inside the factory class.

Upvotes: 0

Views: 197

Answers (1)

hudsonb
hudsonb

Reputation: 2304

You wouldn't have to keep creating methods (though you may want to depending on how complex it is to create a GraphView), but the number of cases in your when will grow.

class GraphViewFactory {
  fun get(data: Graph): GraphView {
     return when {
         is Graph1 -> TODO()
         is Graph2 -> TODO()
         else -> IllegalArgumentException()
     }
  }
}

Using reified types doesn't buy you anything here.

Upvotes: 1

Related Questions