코틀린하고 파이썬을 같이 공부하면서 차이점을 비교하는건 흥미롭다. 근데, 이게 시간이 지날수록 더욱 헷갈리기 시작한다. 그래서 짧지만 생각날 때마다 기록해 두려고. 이번 주제는 ‘not’.
Kotlin
일반적인 비교연산자에 ‘같지 않다’는 둘 다 동일하게 ‘!=’을 쓴다. Kotlin에서는 이와 동일하게, ‘not’의 의미로 ‘!'(exclamation mark)를 쓴다.
if (value !in mylist)
...
if (obj !is String)
...
위의 예제와 같은식이다. ‘not’은 Kotlin 키워드에 존재하지 않는다. operator를 overloading 할 때만 다음과 같이 쓸 뿐.
class MyValue(var value: Int = 0){
operator fun not(): MyValue {
value *= (-1)
return this
}
override fun toString(): String {
return value.toString()
}
}
fun main(args: Array<String>){
val myvalue = MyValue(10)
println(myvalue)
println(!myvalue)
}
10
-10
오버로딩에 리턴값은 중요하지 않고, unary operator이므로 어떤 타입으로 리턴할지는 자유다.
Python
파이썬에서는 ‘!=’ 연산자를 빼고는 ‘!’를 쓰지 않는다. 이에 해당하는 키워드는 ‘not’이다.
mylist = [10, 20, 30]
a = 10
b = a
c = 40
print(b is a)
print(b is not a)
if c not in mylist:
print("a is not in mylist")
True
False
a is not in mylist