# Kotlin運算符

• 算術運算符
• 關係運算符
• 賦值運算符
• 一元運算符
• 按位運算
• 邏輯運算符

## 1. 算術運算符

`+`

`a+b`

`a.plus(b)`

`-`

`a-b`

`a.minus(b)`

`*`

`a*b`

`a.times(b)`

`/`

`a/b`

`a.div(b)`

`%`

`a%b`

`a.rem(b)`

``````fun main(args : Array<String>) {
var a=10;
var b=5;
println(a+b);
println(a-b);
println(a*b);
println(a/b);
println(a%b);
}``````

``````15
5
50
2
0``````

## 2. 關係運算符

`>`

`a>b`

`a.compateTo(b)>0`

`<`

`a<b`

`a.compateTo(b)<0`

`>=`

`a>=b`

`a.compateTo(b)>=0`

`<=`

`a<=b`

`a?.equals(b)?:(b===null)`

`==`

`a==b`

`a?.equals(b)?:(b===null)`

`!=`

`a!=b`

`!(a?.equals(b)?:(b===null))`

``````fun main(args : Array<String>) {
val a = 5
val b = 10
val max = if (a > b) {
println("a is greater than b.")
a
} else{
println("b is greater than a.")
b
}
println("max = \$max")
}``````

``````b is greater than a.
max = 10``````

## 3. 賦值運算符

`+=`

`a+=b`

`a.plusAssign(b)`

`-=`

`a-=b`

`a.minusAssign(b)`

`*=`

`a*=b`

`a.timesAssign(b)`

`/=`

`a/=b`

`a.divAssign(b)`

`%=`

`a%=b`

`a.remAssign(b)`

``````fun main(args : Array<String>) {

var a =20;var b=5
a+=b
println("a+=b :"+ a)
a-=b
println("a-=b :"+ a)
a*=b
println("a*=b :"+ a)
a/=b
println("a/=b :"+ a)
a%=b
println("a%=b :"+ a)

}``````

``````a+=b :25
a-=b :20
a*=b :100
a/=b :20
a%=b :0``````

## 4. 一元運算符

`+`

`+a`

`a.unaryPlus()`

`-`

`-a`

`a.unaryMinus()`

`++`

`++a`

`a.inc()`

`--`

`--a`

`a.dec()`

`!`

`!a`

`a.not()`

``````fun main(args: Array<String>){
var a=10
var b=5
var flag = true
println("+a :"+ +a)
println("-b :"+ -b)
println("++a :"+ ++a)
println("--b :"+ --b)
println("!flag :"+ !flag)
}``````

``````+a :10
-b :-5
++a :11
--b :4
!flag :false``````

## 5. 邏輯運算符

`&&`

(a>b) && (a>c)

`(a>b) and (a>c)`

ΙΙ

(a>b) ΙΙ (a>c)

`(a>b) or(a>c)`

`!`

`!a`

`a.not()`

``````fun main(args: Array<String>){
var a=10
var b=5
var c=15
var flag = false
var result: Boolean
result = (a>b) && (a>c)
println("(a>b) && (a>c) :"+ result)
result = (a>b) || (a>c)
println("(a>b) || (a>c) :"+ result)
result = !flag
println("!flag :"+ result)

}``````

``````(a>b) && (a>c) :false
(a>b) || (a>c) :true
!flag :true``````

## 6. 按位運算

`shl(bits)`

`a.shl(b)`

`shr(bits)`

`a.shr(b)`

`ushr(bits)`

`a.ushr(b)`

`and(bits)`

`a.and(b)`

`or(bits)`

`a.or(b)`

`xor(bits)`

`a.xor(b)`

`inv()`

`a.inv()`

## 7. 按位運算的示例

``````fun main(args: Array<String>){
var a=10
var b=2

println("a.shl(b): "+a.shl(b))
println("a.shr(b): "+a.shr(b))
println("a.ushr(b:) "+a.ushr(b))
println("a.and(b): "+a.and(b))
println("a.or(b): "+a.or(b))
println("a.xor(b): "+a.xor(b))
println("a.inv(): "+a.inv())

}``````

``````a.shl(b): 40
a.shr(b): 2
a.ushr(b:) 2
a.and(b): 2
a.or(b): 10
a.xor(b): 8
a.inv(): -11``````