コンパニオン・オブジェクト内のval arrayListOf()は無効な値を返します

mmaciejow:

私は、コードを持っています:

class DrawerViewModel : ViewModel() {

    fun updateDrawerProfiles() {
        val example = DrawerUtils.exampleProfile
        example.add(  DrawerAccount(3, "NEW Test") )
        setDrawerProfiles(example)
    }

}
class DrawerUtils {

    companion object {

        val exampleProfile = arrayListOf(
            DrawerAccount(1, "Facebook"),
            DrawerAccount(2, "Google")
        )

    }
}

[実行例コード](HTTPS://play.kotlinlang。ORG /#gYXJyYXlMaXN0T2YoXG4gICAgICAgICAgICBEcmF3ZXJBY2NvdW50KDEsIFwiRmFjZWJvb2tcIiksXG4gICAgICAgICAgICBEcmF3ZXJBY2NvdW50KDIsIFwiR29vZ2xlXCIpXG4gICAgICAgIClcbiAgICAgIFxuICAgIH1cbn1cbmRhdGEgY2xhc3MgRHJhd2VyQWNjb3VudCh2YXIgaWQ6IEludCwgdmFyIG5hbWU6IFN0cmluZyApXG5cbiJ9

私が実行したときに数回関数updateDrawerProfilesは、リストのvailidサイズを返します。RUN×3のupdateDrawerProfiles()| OUTPUT:3 4 5

それは3 3 3でなければなりません。

私はコンパニオンオブジェクトoutsiede機能updateDrawerProfilesを移動するとき - それはokです。なぜそれがそのようなものですか?

尊:

それは3 3 3でなければなりません。

違う。

DrawerUtilsコンパニオンはシングルトンです。一度作成したオブジェクトは、既存続けます。あなたはに新しい値を追加しているexampleProfileサイズは、その後4、その後、5、3に成長することは理にかなっているので、3回。

このトピックに関するいくつかの読み取りを行ってくださいhttps://kotlinlang.org/docs/tutorials/kotlin-for-py/objects-and-companion-objects.html

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=343141&siteId=1