官术网_书友最值得收藏!

There's more...

Some of the operators have their corresponding compound assign operators defined. Once we have overloaded the plus and minus operators, we can use the plusAssign (+=) and minusAssign (-=) operators automatically. For example, we can use the plusAssign operator to update the Position instance state as follows:

var position = Position(132.5f, 4f, 3.5f)
position += Position(1f, 1f, 1f)
print(position)

As a result, we will get the position variable with the following state:

Position(x=133.5, y=5.0, z=4.5)

It is important to note that the assign operator returns the Unit. This makes it a better choice than an original basic operator (for example, plus or minus) in terms of memory allocations efficiency when updating an instance. In contrast, the base operators are returning new instances every time.

It is good to know that Kotlin offers operators overloading for Java classes as well. To overload the operator, we just need to add a proper method to the class that has the name of the operator and the public visibility modifier. Here is what the Java version of the Position class with the overloaded plus operator would look like:

public class Position { 
private final float x;
private final float y;
private final float z;

public Position(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}

public int getX() {
return x;
}

public int getY() {
return y;
}

public float getZ() {
return z;
}

        public Position plus(Position pos) { 
return new Position(pos.getX() + x, pos.getY() + y,
pos.getZ() + z);

}
}

And here is how it could be used in Kotlin code:

val position = Position(2.f, 9.f, 55.5f) += (2.f, 2.f, 2.f)

The Kotlin standard library also contains predefined implementations of different operators. One that you should use on a daily basis is the plus operator for a MutableCollection type. This allows for adding new elements to the collection in the following way:

val list = mutableListOf("A", "B", "C")
list += "D"
print(list)

 As a result, the preceding code will print the following output to the console:

[A, B, C, D]
主站蜘蛛池模板: 邹平县| 乐都县| 康平县| 德令哈市| 郑州市| 芒康县| 库伦旗| 神农架林区| 全椒县| 宝山区| 新沂市| 滨海县| 玉田县| 靖远县| 桃江县| 咸宁市| 调兵山市| 贵定县| 万盛区| 红河县| 平乡县| 宁海县| 顺昌县| 庆城县| 梨树县| 昌图县| 鄂尔多斯市| 临沂市| 荥阳市| 平武县| 会昌县| 鄂州市| 郯城县| 施秉县| 万全县| 方正县| 兴和县| 缙云县| 隆昌县| 荆门市| 聂荣县|