ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Follow publication

Member-only story

Kotlin made casting so much neater

--

Casting is a necessary evil in programming world. We love hate it. So Kotlin has made it much nicer than in the Java world. Check out below from something commonly known to something that not as obvious but very handy.

Smart Casting in Kotlin

In Java world, if we want to safely cast to something, it’s good to check before casting to it, then, use it, as below.

private void checkBeforeCast(Object anything) {
if (anything instanceof String) {
println(((String)anything).length());
}
}

You could see from the example above, one despite have check that it isa String type, still have to explicitly cast to it.

In Kotlin

it already smartly know anything is a String and smartly casting it to String with us need to code.

private fun checkBeforeCast(anything: Any) {
if (anything is String) {
println(anything.length)
}
}

Cast or Null in Kotlin: as?

Assuming if we would like to cast a variable to a type and return a null if it is not able to cast.

In Java, one has to explicitly code and check, and return null.

private String castOrNull(Object anything) {
if (anything

--

--

Published in ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

No responses yet

Write a response