[英]Kotlin variance issue
我正在研究節點鏈的概念,每個節點可能具有不同的輸入和輸出類型(盡管輸入/輸出類型都將源自共享的父類型),其中數據從節點傳遞到節點,然后一路轉變。 這是一個例子:
open class Shape
open class Oval : Shape()
class Circle : Oval()
class NodeChain {
val nodes: MutableList<Node<in Shape, out Shape>> = mutableListOf()
fun node(n: Node<in Shape, out Shape>) {
val prevNode = nodes.lastOrNull()
nodes.add(n)
prevNode?.nextNode = n::processInput
}
fun processInput(input: List<Shape>) {
nodes[0].processInput(input)
}
}
abstract class Node<InputType : Shape, OutputType : Shape> {
var nextNode: Function1<List<OutputType>, Unit>? = null
abstract fun processInput(input: List<InputType>)
}
class OvalNode : Node<Shape, Oval>() {
override fun processInput(input: List<Shape>) {
nextNode?.invoke(listOf(Oval()))
}
}
class CircleNode : Node<Oval, Circle>() {
override fun processInput(input: List<Oval>) {
nextNode?.invoke(listOf(Circle()))
}
}
val nodeChain = with (NodeChain()) {
node(OvalNode())
node(CircleNode()) // Error[1] here (listed below)
this
}
Erorr[1]:
Type mismatch.
Required:
Scratch_3.Node<in Scratch_3.Shape, out Scratch_3.Shape>
Found:
Scratch_3.CircleNode
您最終可以看到一個錯誤:嘗試向鏈中添加“ CircleNode”時,它抱怨期望Node<in Shape, out Shape>
並且不允許CircleNode
(即Node<Oval, Circle>
)。 我對方差的理解不足以弄清實現此目標所需的條件(或者是否有可能?)。 這可能嗎? 我在正確的軌道上嗎?
您使用的類型Node<in Shape, out Shape>
等同於Node<Shape, *>
。 因此,您只能添加InputType
為Shape
類型。 對於您的用例,應使用Node<*, *>
添加Node
任何擴展名:
class NodeChain {
val nodes: MutableList<Node<*, *>> = mutableListOf()
fun node(n: Node<*, *>) {
val prevNode = nodes.lastOrNull()
nodes.add(n)
prevNode?.nextNode = n::processInput
}
fun processInput(input: List<Shape>) {
nodes[0].processInput(input)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.