Created
April 26, 2020 14:19
-
-
Save gyugyu90/fa18750101441ef2f59101beea4eb6ec to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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