Mastering Kotlin ~ Convert Java File to Kotlin File Road to Graduation ~ Part 1

Introduction

When using Kotlin on Android etc., there are many people who automatically convert from Java with "Convert Java File to Kotlin File". It actually works, but it's a memo to take it one step further and make better use of Kotlin.

This time you will learn smart cast. Kotlin version: 1.3

Sample code before Kotlin conversion

You might think that there was a better sample (sweat), but suppose you have some Java and Kotlin mixed code like this:

ResponseModle.java


public class ResponseModle {

    public void receiveResponseBody(ItemData data) {
        if (data == null) {
            return;
        }

        if (data.getBody() != null) {
            ResponseLog.INSTANCE.showLength(data.getBody());
        }

        // android.text.TextUtils.isEmpty(CharSequence str)
        //Can check both null or empty
        if (!TextUtils.isEmpty(data.subBody)) {
            ResponseLog.INSTANCE.showSubTitle(data.getSubBody());
        }
    }

ItemData.java


public class ItemData {

    private String body = null;

    private String subBody = null;

    public ItemData(String body, String subBody) {
        this.body = body;
        this.subBody = subBody;
    }

    public String getBody() {
        return body;
    }

    public String getSubBody() {
        return subBody;
    }
}

ResponseLog.kt


object ResponseLog {

    public fun showLength(title: String) {
        System.out.print(title.length)
    }

    public fun showSubTitle(subTitle: String) {
        System.out.print(subTitle)
    }
}

Sample code after Kotlin conversion

If this is automatically converted and matched to the original shape, it will surely look like this ...

ResponseModle.kt


class ResponseModle {

    fun receiveResponceBody(data: ItemData?) {
        if (data == null) {
            return
        }

        if (data?.body != null) {
            ResponseLog.showLength(data.body)
        }

        if (!TextUtils.isEmpty(data?.subBody)) {
            ResponseLog.showSubTitle(data.subBody!!)
        }
    }
}

ItemData.kt


data class ItemData(val body: String? = null, val subBody: String? = null)

ResponseLog.kt


object ResponseLog {

    public fun showLength(title: String) {
        System.out.print(title.length)
    }

    public fun showSubTitle(subTitle: String) {
        System.out.print(subTitle)
    }
}

What's wrong

The implementation of the ResponseModle class has become a slightly aggressive implementation. Nullable is unwrapped (data? ...) by judgment even though the null check of ItemData is completed. Only NonNull can be passed as the argument of the method of ResponseLog class. Forced unwrap (... !!) to avoid compilation errors. I don't want to force unwrap because it has already been checked for null.

Solved by smart cast

If you use smart cast, it will compile without forced unwrapping.

ResponseModle.kt


class ResponseModle {

    fun receiveResponceBody(data: ItemData?) {
        //Smart cast
        if (data !is ItemData) return
        //Smart cast
        if (data.body is String) ResponseLog.showLength(data.body)
        // Kotlin1.Smartcast works with isNullOrEmpty from 3
        if (!data.subBody.isNullOrEmpty()) ResponseLog.showSubTitle(data.subBody)
    }
}

Bad example

Uses the Elvis operator to avoid forced unwrap ResponseLog.showSubTitle(data.subBody ?: "")

bonus

Simple implementation method using let at the time of value assignment

If there is such an implementation

ResponseModle.java


public class ResponseModle {

    public void receiveResponseBody(ItemData data) {
        String body;
        if (data.getBody() == null) {
            return;
        } else {
            body = "OK";
        }
        ResponseLog.INSTANCE.showLength(body);
    }
}

Converting with Convert Java File to Kotlin File

ResponseModle.kt


class ResponseModle {

    fun receiveResponceBody(data: ItemData?) {
        val body: String
        if (data?.body == null) {
            return
        } else {
            body = "OK"
        }
        ResponseLog.showLength(body);
}

However, it becomes a Java-like implementation. If you use Kotlin with much effort, write simply using let

ResponseModle.kt


class ResponseModle {

    fun receiveResponceBody(data: ItemData?) {
        val body = data?.body?.let { "OK" } ?: return
        ResponseLog.showLength(body);
}

Very simple!

Recommended Posts

Mastering Kotlin ~ Convert Java File to Kotlin File Road to Graduation ~ Part 3
Mastering Kotlin ~ Convert Java File to Kotlin File Road to Graduation ~ Part 2
Mastering Kotlin ~ Convert Java File to Kotlin File Road to Graduation ~ Part 1
[Android] Convert Android Java code to Kotlin
Kotlin Class part.2 to send to Java developers
Convert all Android apps (Java) to Kotlin
Road to Java Engineer Part1 Introduction & Environment Construction
<java> Read Zip file and convert directly to string
How to convert a file to a byte array in Java
Convert Java Powerpoint to XPS
How to convert Java radix
[Java] Convert ArrayList to array
Road to Java Engineer Part2 What kind of language is Java?
Java to learn with ramen [Part 1]
Road to Java SE 11 Silver acquisition
How to convert erb file to haml
[Java] Convert 1-to-N List to Map
[Android] Convert Map to JSON using GSON in Kotlin and Java
The road from JavaScript to Java
[Java] Convert array to ArrayList * Caution
The road to Web service creation (Part 2)
Java SE8 Silver ~ The Road to Pass ~
Convert SVG files to PNG files in Java
Kotlin scope functions to send to Java developers
Sample to unzip gz file in Java
Memo for migration from java to kotlin
<Java> Quiz to batch convert file names separated by a specific character string with a part of the file name
Kotlin functions and lambdas to send to Java developers
[Ruby] How to convert CSV file to Yaml (Yml)
Introduce Kotlin to your existing Java Maven Project
Migrate from Java to Server Side Kotlin + Spring-boot
Write to a file using ShiftJIS-Read a file (Kotlin / JVM)
[Java] Convert DB code to code value using enum
Initial settings for rewriting Java projects to Kotlin
How to convert a solidity contract to a Java contract class
A story about trying to operate JAVA File
Getting started with Kotlin to send to Java developers
What I did when I converted java to Kotlin
Convert Java nested beans to aaa.bbb [0] .ccc format
Where Java programmers tend to trip over Kotlin
How to write Java String # getBytes in Kotlin?
What Java inexperienced people did to study Kotlin
[Java] Convert and import file values with OpenCSV
The road to creating a Web service (Part 1)