关于android:无法使用var在Kotlin中设置对象的属性

Cannot set property of object in Kotlin using var

我正在尝试设置使用Kotlin在Android Studio中创建的对象的属性。我每次都使用for循环制作一个新对象并将其添加到数组中。当我初始化对象并尝试设置topId时,即使我将其声明为var,它也会显示" Val无法重新分配"。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 for (i in 1..5) {


                var topRanNum = generateRandomNum(topSize)
                var top = currentSeasonTops[topRanNum]
                var topLoopCounter = 0
                var topId = top.id
                var newOutfit: Outfit = Outfit()

                if(top.wornCount < 5 ) {

                    newOutfit.topId = top.id


                }

            }

服装类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 public Outfit() {}

    public Outfit(Long topId, Long bottomId, String topPhotoPath, String bottomPhotoPath) {
        this.topId = topId;
        this.bottomId = bottomId;
        this.topPhotoPath = topPhotoPath;
        this.bottomPhotoPath = bottomPhotoPath;

    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTopPhotoPath() {
        return topPhotoPath;
    }

    public String getBottomPhotoPath() {
        return bottomPhotoPath;
    }

 public Long getTopId() {
        return topId;
    }

    public Long getBottomId() {
        return bottomId;
    }


之所以会发生这种情况,是因为您需要在Java中为topId从外部声明一个可访问的setter或使该变量可以从外部访问。

例如

1
2
3
public void setTopId(Long topId) {
    this.topId = topId;
}