Thursday 15 July 2021

Android Java to Kotlin migration by example part 8: type checks and smart cast

Let's consider the following Java code:

import static java.lang.System.out;

public class MainClass {

static void printPiTimesValue(Object value){
if(value instanceof Float)
out.println(3.14f*(Float)value);
if(value instanceof Double)
out.println(3.14*(Double)value);
if(value instanceof String)
out.println(3.14*Double.parseDouble((String)value));
}

public static void main(String[] args){
printPiTimesValue(2.0);
printPiTimesValue(2.0f);
printPiTimesValue("2.0");
}
}
(I've imported System.out, to write out.println instead of System.out.println every time).

So our printPiTimesValue gets something as param (Object, which in Java can be basically anything), and checks its type with the instanceof operator. If the param is float or double, the method casts it, multiplies by 3.14 and prints value. If it's String, the method casts it to String, then parses Double and prints the multiplied value again.

The program execution results in following output:

6.28
6.28
6.28

Now let's look at the Kotlin couterpart of our code:

package com.mypackage

fun printPiTimesValue(value: Any){
if(value is Float)
println(3.14f*value)
if(value is Double)
println(3.14*value)
if(value is String)
println(3.14*value.toDouble())
}


fun main() {
printPiTimesValue(2.0)
printPiTimesValue(2.0f)
printPiTimesValue("2.0")
}
It works the same way and gives the same results. We use Any in place of Object. Instead of Java instanceof operator, we use Kotlin is, which seems to do the same (return true if the left operand is the type specified by right operand).
Other than that, it looks similar, right?

Well, not exactly.
Where are the casts?
In Java, we had a cast everytime we wanted to use our Object as, for instance, Float, we had to:
1) check its type with instanceof
2) cast it.

In Kotlin - if the type check with  is succeeds, the value is automatically casted using a mechanism called smart cast!
The only case where we actually had change the type is the third if, where the smart cast already casted our value to String, but we still have to parse it as Double (as we had to in Java).


No comments:

Post a Comment

Python crash course part 10: inheritance and polymorphism

In the last part we've shown how to create and use a class in Python. Today we're going to talk about inheritance: wchich means cre...