파게로그

[Basic] 연산자 본문

콤퓨타 왕기초/Kotlin

[Basic] 연산자

파게 2021. 6. 7. 13:00

Arithmetic Operators

+, -, *, /, %

 

참고로 +의 경우 String의 연결(concatenation)을 위해서도 사용된다.

 

fun main(args : Array<String>) {
    val hello = "안녕하세요"
    val hi = "하잉ㅋㅋ"
    
    val say = hello + hi
    
    println(say) // 안녕하세요하잉ㅋㅋ
}

그리고 객체와 같은, user-defined types에 대해서, plus() 함수를 오버로딩하여 + 연산자를 사용할 수 있다. Java와 달리 연산자 오버로딩이 가능하다고 이해할 수 있겠다. 이에 대해서는 Kotlin OOP 포스팅에서 자세히 다룬다.

 

Expression Function name Translates to
a + b plus a.plus(b)
a - b minus a.minus(b)
a * b times a.times(b)
a / b div a.div(b)
a % b mod a.mod(b)

 

Assignment Operators

=, +=, -=, *=, /=, %=

 

Expression Equivalent to Translates to
a += b a = a + b a.plusAssign(b)
a -= b a = a - b a.minusAssign(b)
a *= b a = a * b a.timesAssign(b)
a /= b a = a / b a.divAssign(b)
a %= b a = a % b a.modAssign(b)

 

Unary prefix and Increment/Decrement Operators

+, -, !, ++, --

 

Operator Meaning Expression Translates to
+ Unary plus +a a.unaryPlus()
- Unary minus (inverts sign) -a a.unaryMinus()
! not (inverts value) !a a.not()
++ Increment: increases value by 1 ++a a.inc()
-- Decrement: decreases value by 1 --a a.dec()

 

Comparison and Equality Operators

>, <, >=, <=, ==, !=

 

Operator Meaning Expression Translates to
> greater than a > b a.compareTo(b) > 0
< less than a < b a.compareTo(b) < 0
>= greater than or equals to a >= b a.compareTo(b) >= 0
<= less than or equals to a <= b a.compareTo(b) <= 0
== is equal to a == b a?.equals(b)?:(b===null)
!= not equal to a != b !(a?.equals(b)?:(b===null))

 

Logical Operators

||, &&

 

in Operator

in, !in

 

object가 collection에 속하는지 속하지 않는지를 확인할 때 사용한다.

 

Operator Expression Translates to
in a in b b.contains(a)
!in a !in b !b.contains(a)

 

Index access Operator

Expression Translated to
a[i] a.get(i)
a[i, n] a.get(i, n)
a[i1, i2, ..., in] a.get(i1, i2, ..., in)
a[i] = b a.set(i, b)
a[i, n] = b a.set(i, n, b)
a[i1, i2, ..., in] = b a.set(i1, i2, ..., in, b)

 

Invoke Operator

Expression Translated to
a() a.invoke()
a(i) a.invoke(i)
a(i1, i2, ..., in) a.invoke(i1, i2, ..., in)
a[i] = b a.set(i, b)

 

Bitwise Operator

bitwise 연산자는 존재하지 않는다. 대신 다음의 함수들을 사용한다.

참고: https://www.programiz.com/kotlin-programming/bitwise

 

▪ shl: Signed shift left

▪ shr: Signed shift right

▪ ushr: Unsigned shift right

▪ and: Bitwise and

▪ or: Bitwise or

▪ xor: Bitwise xor

▪ inv: Bitwise inversion

 

Ternary Operation

삼항연산자는 존재하지 않는다.

'콤퓨타 왕기초 > Kotlin' 카테고리의 다른 글

[Basic] Input and Output  (0) 2021.06.07
[Basic] Expression, Statement, Block  (0) 2021.06.07
[Basic] 형 변환(type casting)  (0) 2021.06.07
[Basic] 자료형, 변수 선언  (0) 2021.06.07
Kotlin 학습을 위한 자료  (0) 2021.06.06
Comments