【问题标题】:Access Parent class variables in companion Object in Kotlin在 Kotlin 中访问伴随对象中的父类变量
【发布时间】:2019-12-31 13:52:45
【问题描述】:

我正在尝试在其他类中调用一个类的静态函数,例如 java,但是在 kotlin 中我不能创建一个静态函数,我必须创建一个伴随对象,我必须在其中定义我的函数,但是在这样做的同时我无法访问父类变量,有什么方法可以在 kotlin 中实现这一点。

class One {

    val abcList = ArrayList<String>()

    companion object {

        fun returnString() {
            println(abcList[0]) // not able to access abcList here
        }
    }
}

class Two {

    fun tryPrint() {
        One.returnString()
    }
}
// In Java we can do it like this

class One {

    private static ArrayList<String> abcList = new ArrayList<>();

    public void tryPrint() {
        // assume list is not empty 
        for(String ab : abcList) {
            System.out.println(ab);
        }
    }

    public static void printOnDemand() {
        System.out.println(abcList.get(0));
    }
}

class Two {

    public void tryPrint(){
        One.printOnDemand();
    }
}

我想访问有趣的 returnString() 像我们在 java 中做的一类的静态函数,如果有人实现了这个,请帮助。

【问题讨论】:

  • 你也不能在 java 中这样做,除非 abcList 也是静态的。尝试将 abcList 移动到伴随对象中
  • 如何在 kotlin 类中将 abcList 设为静态,因为我在第一类中的其他函数也在使用 abcList 进行某些操作@TimCastelijns
  • 静态函数无法访问非静态函数/变量,Kotlin 也是如此。
  • 你为什么不扩展one

标签: android kotlin


【解决方案1】:

在您的情况下,abcList 是该类的成员变量。类的每个实例都有自己的成员变量版本,这意味着静态方法无法访问它们。如果您想从伴生对象访问它,它也必须是静态的。

class One {
    companion object {
        val abcList = ArrayList<String>()

        fun returnString() {
            println(abcList[0])
        }
    }
}

class Two {
    fun tryPrint() {
        One.returnString()
    }
}

此代码将起作用,但请记住,在这种情况下,abcList 将只有一个实例。无法从静态函数访问成员变量(即使在 Java 中也不行)。

这是您的 Java 示例的 Kotlin 版本:

class One {
    companion object {
        val abcList = ArrayList<String>()

        fun printOnDemand() {
            println(abcList[0])
        }
    }

    fun tryPrint() {
        for (ab in abcList) {
            println(ab)
        }
    }
}

class Two {
    fun tryPrint() {
        One.printOnDemand()
    }
}

【讨论】:

  • 我想在第一类全局使用 abcList
  • 全局你的意思是你想从类 One 的每个实例中更改相同的 ArrayList?
  • 我想在第一类的其他函数中使用 abcList,并在第二类的 abcList 中添加或删除字符串。我可以通过将 abcList 设为静态和 One 类中的静态函数在 java 中轻松做到这一点
  • 我给你的答案是一样的,通过将列表移动到伴生对象中,我也将列表设为静态。
  • 现在请检查已编辑的问题,我想要实现什么。 @pshegger
【解决方案2】:

规则:您不能访问静态属性,非静态成员中的类成员,并且您不能访问非静态属性,静态成员中的类成员,这是伴随对象类。 这个规则在 Java 和 Kotlin 中都有。如果要访问类的非静态成员 在静态成员中,您必须在伴随对象类中声明它。

【讨论】:

    【解决方案3】:

    为您的情况使用以下代码。

    object One {
        val abcList: MutableList<String> = mutableListOf()
    
        fun returnString() {
           println(abcList[0])
        }
    
        fun printOnDemand() {
           println(abcList[0]);
        }
    }
    
    class Two {
        fun tryPrint() {
            One.printOnDemand()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-30
      • 2019-06-02
      • 2016-05-21
      • 1970-01-01
      相关资源
      最近更新 更多