1.算术运算符
加(+)、减(-)、乘(*)、除(/)、取模(%)
栗子:
fun main() {
val number1 = 12.5
val number2 = 3.5
var result: Double
result = number1 + number2
println("number1 + number2 = $result")
result = number1 - number2
println("number1 - number2 = $result")
result = number1 * number2
println("number1 * number2 = $result")
result = number1 / number2
println("number1 / number2 = $result")
result = number1 % number2
println("number1 % number2 = $result")
}
结果:
number1 + number2 = 16.0
number1 - number2 = 9.0
number1 * number2 = 43.75
number1 / number2 = 3.5714285714285716
number1 % number2 = 2.0
"+"还可以用于字符串连接
fun main() {
val start = "Talk is cheap. "
val middle = "Show me the code. "
val end = "- Linus Torvalds"
val result = start + middle + end
println(result)
}
结果:
谈话很便宜。告诉我代码。 - Linus Torvalds
重载+运算符
fun main() {
val p1 = Point(3, -8)
val p2 = Point(2, 9)
var sum = Point()
sum = p1 + p2
println("sum = (${sum.x}, ${sum.y})")
}
class Point(val x: Int = 0, val y: Int = 10) {
// overloading plus function
operator fun plus(p: Point) : Point {
return Point(x + p.x, y + p.y)
}
}
输出:sum =(5,1)
这里,plus()函数用operator关键字标记,告诉编译器+运算符正在被重载。
表达式p1 + p2转化为p1.plus(p2)。
一元运算符
fun main() {
val a = 1
val b = true
var c = 1
var result: Int
var booleanResult: Boolean
result = -a
println("-a = $result")
booleanResult = !b
println("!b = $booleanResult")
--c
println("--c = $c")
}
结果:
-a = -1
!b = false
--c = 0
比较运算符
> 大于 a> b a.compareTo(b)> 0
< 少于 a <b a.compareTo(b)<0
> = 大于或等于 a> = b a.compareTo(b)> = 0
<= 小于或等于 a <= b a.compareTo(b)<= 0
== 等于 a == b a?.equals(b)?:( b === null)
!= 不等于 a!= b !(a?.equals(b)?:( b === null))
逻辑运算符
两个逻辑运算符:||和&&
|| 如果其中一个布尔表达式是 true就为true
&& 如果所有布尔表达式都为true才为 true
in操作符
in a在b中
!in a不在b中
fun main() {
val numbers = intArrayOf(1, 4, 42, -3)
if (4 in numbers) {
println("numbers array contains 4.")
}
}
结果:
numbers array contains 4.
网友评论