Kotlin中类外的对象的静态列表 [英] Static List of Objects out Class in Kotlin
问题描述
所有类对象的静态列表
如果可以,可以与Kotlin一起使用吗?
Static List of all Objects of Class
Is this working with Kotlin if yes can you provide an example?
现在,我的界面没有列表,我在两种实现中都创建了一个伴随对象.但这感觉有点不对....请帮我弄清楚:)
Right now my interface does not have the List and i am creating a companion Object in both implementations. But it feels wrong somehow.... Pls help me to figure this out :)
我现在有四种方式可以做到这一点,在这里我将展示两种方式,因为第四种方式需要更复杂的 UML .我也许这实际上是您如何做的,如果可能没有一个人有主意;)
I have four ways right now to do this i will show two here because the fourth one would require a more complex UML. Mybe this is actually how you do it if not maybe one of you has an idea ;)
我在Kotlin中的代码采用一种方法:
My Code in Kotlin approach one:
interface IMyClass {
}
class MyClassOne : IMyClass {
companion object {
var myClassList: ArrayList<IMyClass> = ArrayList()
}
constructor() {
println(myClassList)
}
}
class MyClassTwo : IMyClass {
companion object {
var myClassList: ArrayList<IMyClass> = ArrayList()
}
constructor() {
println(myClassList)
}
}
我在Kotlin中的代码采用两种方法:
My Code in Kotlin approach two:
interface IMyClass {
companion object {
var myClassList: ArrayList<IMyClass> = ArrayList()
}
}
class MyClassOne : IMyClass {
constructor() {
println(IMyClass.myClassList)
}
}
class MyClassTwo : IMyClass {
constructor() {
println(IMyClass.myClassList)
}
}
我在Kotlin中的代码采用三种方法:
My Code in Kotlin approach three:
interface IMyClass {
var myClassList: ArrayList<IMyClass>
}
class MyClassOne {
companion object : IMyClass{
override var myList: ArrayList<IMyClass>
get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates.
set(value) {}
}
}
class MyClassTwo {
companion object : IMyClass{
override var myList: ArrayList<IMyClass>
get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates.
set(value) {}
}
}
我的Java代码:
public interface IMyClass {
List<IMyClass> myClassList = new ArrayList<>();
}
public class MyClassOne implements IMyClass {
public MyClassOne() {
System.out.println(myClassList );
}
}
public class MyClassTwo implements IMyClass {
public MyClassTwo() {
System.out.println(myClassList);
}
}
推荐答案
我个人决定选择第三个选项:
Personally i decided to go for my third option:
interface IMyClass {
var myClassList: ArrayList<IMyClass>
}
class MyClassOne {
companion object : IMyClass{
override var myList: ArrayList<IMyClass>
get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates.
set(value) {}
}
}
class MyClassTwo {
companion object : IMyClass{
override var myList: ArrayList<IMyClass>
get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates.
set(value) {}
}
}
这篇关于Kotlin中类外的对象的静态列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!