
fun main()
{
//Hello Kotlin으로 먼저 할당 후 null지정함
//결론 str1는 null이다.
var str1 : String? = "Hello Kotlin"
str1 = null
//조건식을 통해 null 상태를 검사
var len = if(str1 != null)str1.length else -1
println("str1: $str1 lenghth: $len")
//출력 결과 str1: null lenghth: -1
}
fun main()
{
var str1 : String? = "Hello World"
str1 = null
//세이프 콜과 엘비스 연산자 활용
//null아니면 length출력, null이면 -1 출력
println("str1 : ${str1} length : ${str1?.length ?: -1}")
// 출력 결과 str1 : null length : -1
}
to자료형()
코틀린에서는 명시적 함수를 사용하여 기본 자료형 간의 변환을 수행할 수 있다.
toByte() : Byte 타입으로 변환
toUByte() : unsigned 타입인 UByte 타입으로 변환
toShort() : Short 타입으로 변환
toUShort() : unsigned 타입인 UShort 타입으로 변환
toInt() : Int 타입으로 변환
toUInt() : unsigned 타입인 UInt 타입으로 변환
toLong() : Long 타입으로 변환
toULong() : unsigned 타입인 ULong 타입으로 변환
toFloat() : Float 타입으로 변환
toDouble() : Double 타입으로 변환
toChar() : Char 타입으로 변환
toString() : String 타입으로 변환
toBigInteger() : BigInteger 타입으로 변환
toBigDecimal() : BigDecimal 타입으로 변환
as 키워드를 사용한다. 변환이 실패하면 ClassCastException이 발생할 수 있다.
as? 키워드를 사용한다. 변환이 실패하면 null을 반환된다.