我正在使用Kotlin和TornadoFX编写PC应用程序。
我会告诉你我拥有的东西
FooModel.kt
:
class FooModel(val id: Int){
constructor(foo: Foo) : this(foo.id)
}
Foo.kt
:
data class Foo(val id: Int)
MainController.kt
:
val FoosList: ObservableList<FooModel> = FXCollections.observableArrayList<FooModel>()
//bellow I wanna describe what I’m already doing with val above
fun fooDifferentOperationsForExample(example: Int){
example1Object = FoosList.find{ it.id == example }
example2Object.removeIf { it.id == example }
example3Object.setAll(it.map {FooModel})
}
我正在列表视图中显示model
的描述,并希望在同一列表中添加其他类型的对象。我有一个sealed class
的解决方案,例如DifferentKindsOfInstances.kt
的示例:
sealed class DifferentKindsOfInstances{
data class Foo(val foo: FooModel): DiffrentKindsOfInstances()
data class Bar(val bar: BarModel): DiffrentKindsOfInstances()
}
让我们以为BarModel
是FooModel
的精确副本,没关系。
但是,如果我想以以前的工作方式(在MainControl
中)继续使用FooModel,那么代码将如何显示?
it.foo.id
对我不起作用
答案 0 :(得分:1)
这是在两个地方引用密封类成员的解决方案:在cellFragment {}中渲染ListCell以及将所选密封类项目绑定到文本字段字符串内容。
class ItemModel1 ( val dataField1 : String )
class ItemModel2 ( val dataField2 : String )
sealed class ItemViewInstance {
data class Item1(val item1: ItemModel1): ItemViewInstance()
data class Item2(val item2: ItemModel2): ItemViewInstance()
}
class SealedClassDemoView : View("Sealed Class") {
val instances = listOf(
ItemViewInstance.Item1(ItemModel1("One")),
ItemViewInstance.Item2(ItemModel2("Two"))
).observable()
val selectedItemString = SimpleStringProperty()
override val root = vbox {
listview(instances) {
cellFormat {
when( it ) {
is ItemViewInstance.Item1 -> text = it.item1.dataField1
is ItemViewInstance.Item2 -> text = it.item2.dataField2
}
}
selectedItemString.bind(
Bindings.createStringBinding(
Callable {
val sel = selectionModel.selectedItemProperty().value
when (sel) {
is ItemViewInstance.Item1 -> sel.item1.dataField1
is ItemViewInstance.Item2 -> sel.item2.dataField2
else -> ""
}
},
selectionModel.selectedItemProperty()
)
)
}
textfield(selectedItemString)
padding = Insets(2.0)
spacing = 4.0
}
}
class SealedClassDemoApp : App(SealedClassDemoView::class)
fun main(args: Array<String>) {
launch<SealedClassDemoApp>(args)
}