算数运算符
名称 |
符号 |
方法 |
用法一 |
用法二 |
加 |
+ |
plus |
var a = 5 + 2 |
var a = 5.plus(2) |
减 |
- |
minus |
var a = 5 - 2 |
var a = 5.minus(2) |
乘 |
* |
times |
var a = 5 * 2 |
var a = 5.times(2) |
除 |
/ |
div |
var a = 5 / 2 |
var a = 5.div(2) |
取余(取模) |
% |
mod |
var a = 5 % 2 |
var a = 5.mod(2) |
自加 |
++ |
inc |
++a、a++ |
a = a.inc() |
自减 |
-- |
dec |
--a、a-- |
a = a.dec() |
关系运算符
名称 |
符号 |
等于 |
== |
不等于 |
!= |
大于 |
> |
大于或等于 |
>= |
小于 |
< |
小于或等于 |
<= |
示例
if(a == b){
print("a == b")
}
逻辑运算符
名称 |
符号 |
Kotlin |
用法 |
逻辑与 |
&& |
&& |
|
逻辑或 |
|| |
|| |
|
逻辑非 |
! |
not |
var a = false; if (a.not()) { } |
逻辑异或 |
^ |
xor |
|
逻辑与 |
& |
and |
|
逻辑或 |
| |
or |
|
位运算符
名称 |
Java |
Kotlin |
用法 |
位与 |
& |
and |
1 and 2 / 1.and(2) |
位或 |
| |
or |
1 or 2 / 1.or(2) |
位非、位取反 |
~ |
inv |
1.inv() |
位异或 |
^ |
xor |
1 xor 2 / 1.xor(2) |
右移 |
>> |
shr |
1 shr 2 / 1.shr(2) |
左移 |
<< |
shl |
1 shl 2 / 1.shl(2) |
0填充的右移 |
>>> |
ushr |
1 ushr 2 / 1.ushr(2) |
三目运算
Java
int a = -1;
String res = a > 0 ? "a > 0" : "a <= 0";
Kotlin
val a = -1
val res = if (a > 0) "a > 0" else "a <= 0"
forEach、in 循环
val array = arrayOf(1, 2, 3)
for (i in array.indices) {
print(array[i])
}
for (i in array) {
print(i)
}
array.forEach {
print(it)
}
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
区间运算符
for (i in 0..10) { // for (int i = 0; i <= 10; i++)
print(i)
}
for (i in 0.rangeTo(10)) { // for (int i = 0; i < 10; i++)
print(i)
}
for (i in 0 until 10) { // for (int i = 0; i < 10; i++)
print(i)
}
for (i in 10 downTo 0) { // for (int i = 10; i >= 0; i--)
print(i)
}
for (i in 'a'..'z') { // 等同于 'a' <= i && i <= 'z'
print(i)
}
for (i in 0..10 step 2) { // for (int i = 0; i <= 10; i+=2)
print(i)
}
for (i in 10 downTo 0 step 2) { // for (int i = 10; i >= 0; i-=2)
print(i)
}
In 操作符
val a = arrayOf(1, 2, 3)
if (1 in a) {
println("a 包含 1")
}
// 等价
if (a.contains(1)) {
println("a 包含 1")
}
符号重载
class User(name: String) {
var name: String? = name
operator fun plus(user: User): String {
return this.name + " + " + user.name
}
operator fun minus(user: User): String {
return this.name + " - " + user.name
}
}
val user1 = User("Wiki")
val user2 = User("Sui")
println(user1 + user2) // Wiki + Sui
println(user1 - user2) // Wiki - Sui
网友评论