Skip to content

Instantly share code, notes, and snippets.

@gyugyu90
Created April 26, 2020 14:19
Show Gist options
  • Save gyugyu90/fa18750101441ef2f59101beea4eb6ec to your computer and use it in GitHub Desktop.
Save gyugyu90/fa18750101441ef2f59101beea4eb6ec to your computer and use it in GitHub Desktop.
fun getStringLength(obj: Any): Int? {
if (obj is String) {
// 블록에 접근하게 되면 String 타입으로 안전하게 형변환됨
return obj.length
}
// 형변환되는 블록 밖에서는 Any 타입을 그대로 사용
return null
}
fun main() {
fun printLength(obj: Any) {
println("'$obj' String의 길이는 ${getStringLength(obj) ?: "... 에러입니다. 스트링이 아니네요..;;"} ")
}
printLength("아무스트링")
printLength(1000)
printLength(listOf(Any()))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment