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

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. 3rd time This time, you will learn how to process List and for statements. Kotlin version: 1.4

Sample code before Kotlin conversion

An example where there is a process to generate a List from a certain object. There are some conditions for creating a List.

ItemData.java


//Object with 7 Strings
public class ItemData {
    private String item1;
    private String item2;
    private String item3;
    private String item4;
    private String item5;
    private String item6;
    private String item7;

    public ItemData2(String item1, String item2, String item3, String item4,
                     String item5, String item6, String item7) {
        this.item1 = item1;
        this.item2 = item2;
        this.item3 = item3;
        this.item4 = item4;
        this.item5 = item5;
        this.item6 = item6;
        this.item7 = item7;
    }

    public String getItem1() {
        return item1;
    }

    public String getItem2() {
        return item2;
    }

    public String getItem3() {
        return item3;
    }

    public String getItem4() {
        return item4;
    }

    public String getItem5() {
        return item5;
    }

    public String getItem6() {
        return item6;
    }

    public String getItem7() {
        return item7;
    }
}

ListUtil.java


//Util to create List from object
public final class ListUtil {

    private ListUtil() {
    };

    private static final int MAX_SIZE = 4;

    //Make a list with item1, item2, item3, item4, item5 of the object
    //However, if it is null, it will not be added to the List.
    public static List<String> createItemList(final ItemData itemData) {
        if (itemData == null) {
            return new ArrayList<>();
        }
        final List<String> list = new ArrayList<>();
        for (int i = 0; i <= MAX_SIZE; i++) {
            switch (i) {
                case 0:
                    if (itemData.item1 != null) {
                        list.add(itemData.item1);
                    }
                    break;
                case 1:
                    if (itemData.item2 != null) {
                        list.add(itemData.item2);
                    }
                    break;
                case 2:
                    if (itemData.item3 != null) {
                        list.add(itemData.item3);
                    }
                    break;
                case 3:
                    if (itemData.item4 != null) {
                        list.add(itemData.item4);
                    }
                    break;
                case 4:
                    if (itemData.item5 != null) {
                        list.add(itemData.item5);
                    }
                    break;
                default:

            }
        }
        return list;
    }
}

Sample code after Kotlin automatic conversion

If this is automatically converted, it will look like this ... For the time being, it still works.

ItemData.kt


//Object with 7 Strings
class ItemData(
    val item1: String,
    val item2: String,
    val item3: String,
    val item4: String,
    val item5: String,
    val item6: String,
    val item7: String
)

ListUtil.kt


//Util to create List from object
object ListUtil {
    private const val MAX_SIZE = 4
    //Make a list with item1, item2, item3, item4, item5 of the object
    //However, if it is null, it will not be added to the List.
    fun createItemList(itemData: ItemData?): List<String?> {
        if (itemData == null) {
            return ArrayList()
        }
        val list: MutableList<String?> = ArrayList()
        for (i in 0 until MAX_SIZE) {
            when (i) {
                0 -> if (itemData.item1 != null) {
                    list.add(itemData.item1)
                }
                1 -> if (itemData.item2 != null) {
                    list.add(itemData.item2)
                }
                2 -> if (itemData.item3 != null) {
                    list.add(itemData.item3)
                }
                3 -> if (itemData.item4 != null) {
                    list.add(itemData.item4)
                }
                4 -> if (itemData.item5 != null) {
                    list.add(itemData.item5)
                }
                else -> {
                }
            }
        }
        return list
    }
}

Think about how to implement

Since it is implemented in Kotlin, I want to make it simpler. I will fix it immediately

ItemData.kt


//Specify data as a data class with data
data class ItemData(
    val item1: String,
    val item2: String,
    val item3: String,
    val item4: String,
    val item5: String,
    val item6: String,
    val item7: String
)

ListUtil.kt


//Util to create List from object
object ListUtil {
    private const val MAX_SIZE = 4
    //Make a list with item1, item2, item3, item4, item5 of the object
    //However, if it is null, it will not be added to the List.

    //The return value is List<String?>→List<String>Is good
    fun createItemList(itemData: ItemData?): List<String> =
        itemData?.let {
            //If null, don't enter here
            mutableListOf<String?>().also { list ->
                // for (i in 0..MAX_SIZE)Can also be described as
                (0 until MAX_SIZE).forEach { i ->
                    when (i) {
                        0 -> it.item1
                        1 -> it.item2
                        2 -> it.item3
                        3 -> it.item4
                        4 -> it.item5
                        else -> null
                    }.also {
                        list += it
                    }
                }
            }.filterNotNull()
            //This will eliminate the null in the List and make the String NonNull.
            //You don't have to check for null when adding
        } ?: emptyList()
    //Returns an empty List if null
    //Empty List is ArrayList()Not emptyList()return it
}

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
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
Kotlin Class to send to Java developers
How to convert erb file to haml
Log output to file in Java
[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
[Java] How to use the File class
The road to Web service creation (Part 2)
Java SE8 Silver ~ The Road to Pass ~
Convert from java UTC time to JST time
[Java] Convert Object type null to String type
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
[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)