如何通过子类型避免 kotlin factory class 方法?
How to avoid kotlin factory class method by subtype?
我有一个关于科特林的问题:
假设你有这个:
sealed class Graph : Serializable
data class Graph1() : Graph() {}
data class Graph2() : Graph() {}
并且您想要一个工厂 class 给定 Graph 的子类型为您提供 GraphView。
所以,你有类似的东西
interface GraphViewFactory{
fun get(data: Graph1):GraphView
fun get(data: Graph2):GraphView
}
你也有相应的实现。
在 kotlin 中是否有可能使用内联和具体化来避免这种接口的方法爆炸,每个图形类型都有一个接口?我正在尝试,但我做不到。
一方面,kotlin 接口(我认为)不允许内联函数,另一方面,即使没有接口,我也无法将参数 T 自动转换为特定子类型之一 class工厂里面class.
您不必继续创建方法(尽管您可能希望根据创建 GraphView
的复杂程度来创建方法),但是 when
中的案例数量会增加.
class GraphViewFactory {
fun get(data: Graph): GraphView {
return when {
is Graph1 -> TODO()
is Graph2 -> TODO()
else -> IllegalArgumentException()
}
}
}
在这里使用具体化的类型不会给你带来任何好处。
我有一个关于科特林的问题:
假设你有这个:
sealed class Graph : Serializable
data class Graph1() : Graph() {}
data class Graph2() : Graph() {}
并且您想要一个工厂 class 给定 Graph 的子类型为您提供 GraphView。
所以,你有类似的东西
interface GraphViewFactory{
fun get(data: Graph1):GraphView
fun get(data: Graph2):GraphView
}
你也有相应的实现。
在 kotlin 中是否有可能使用内联和具体化来避免这种接口的方法爆炸,每个图形类型都有一个接口?我正在尝试,但我做不到。
一方面,kotlin 接口(我认为)不允许内联函数,另一方面,即使没有接口,我也无法将参数 T 自动转换为特定子类型之一 class工厂里面class.
您不必继续创建方法(尽管您可能希望根据创建 GraphView
的复杂程度来创建方法),但是 when
中的案例数量会增加.
class GraphViewFactory {
fun get(data: Graph): GraphView {
return when {
is Graph1 -> TODO()
is Graph2 -> TODO()
else -> IllegalArgumentException()
}
}
}
在这里使用具体化的类型不会给你带来任何好处。