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")
)
}
}
私が実行したときに数回関数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