본문 바로가기

# 02/코틀린

[Kotlin] 변수와 타입 2

반응형

null 처리 방법


Java와 Kotlin의 처리방법 비교


- Java에서는 @NotNull과 @Nullable 어노테이션을 통해 알리지만 Kotlin에서는 기본적으로 NotNull이고 Nullable 표현에만 '?'가 사용된다.


java

public void set ( @NotNull String a, @Nullable String b ) {

// Do noting

}


String temp = null;

int size = -1;

if ( temp != null ) {

size = temp.length();

}

// or


if (!TextUtils.isEmpty ( temp ) ) {

size = temp.length();

}



kotlin

fun set ( a : String, b : String? ) {

// Do noting

}


var temp : String? = null

var size = -1

if ( temp != null ) {

size = temp.length

}


// or


var temp : String? = null

val size = if ( temp != null) temp.length else -1





$예제

var a = 1

var s1 = "a is $a"

var s2 = "$s1.replace("is", "was")} but now is $a"

var s3 = """Hello

World ${'$'}s1

Test

"""





null 가능한 변수의 예제

fun parseInt ( str : String ) : Int? {

return str.toIntOrNull()

}


fun printProduct ( arg1 : String, arg2 : String ) {

val x = parseInt ( arg1 )

val y = parseInt ( arg2 )


// Using 'x * y' yields error because they may hold nulls.

if ( x != null && y != null ) {

// x and y are automatically cast to non-nullable after null chexk

println( x * y )

}

else {

println ( "either '$arg1' or '$arg2' is not a number" )

}

}

fun main ( args : Array<String> ) {

printProduct ( "6", "7" )

printProduct ( "a", "7" )

printProduct ( "a", "b" )

}







요약


- 코틀린에서 변수 선언은 기본적으로 NotNull 이다.

- Nullable 표현을 하려면 ?를 사용한다.


- var str1 : String?로 선언되었다면 str1.length를 그냥 사용할 수 없다.

- str1?.length 또는 str1!!.length 또는 (str1 as String).length로 사용


- 또 다른 null의 검사는 Safe Call(?.)을 사용해 null이 아닌 경우에만 호출


- Elvis 연산자(?:)를 사용하면 '참 ?: 거짓' 형태로 참이면 앞의 문장을 반환



반응형

'# 02 > 코틀린' 카테고리의 다른 글

[Kotlin] 변수와 타입 3  (0) 2019.08.12
[Kotlin] 변수와 타입 1  (0) 2019.08.12
[Kotlin] 언어의 특징  (0) 2019.08.12
[Kotlin] super와 this의 참조  (0) 2019.08.08
[Kotlin] 상속과 다형성  (0) 2019.08.07