Kotlin versus Java

Recently, due to work relationship, I need to maintain the company’s existing Kotlin customer service chat project iteratively. I’ve been using Java all my life, so KOtlin is still new to me. After using Kotlin for a while, I still feel a little bit. Kotlin is really too concise than Java, a piece of code, at first may be written according to the Java syntax habits, and then according to the IDE prompt, step by step optimization, reduce the amount of code, and finally found that the amount of code is very large. The only code left may be business logic. With Kotlin’s MVVM architecture, the project is very simple. Kotlin is a JVM-based programming language that, like Java, can be compiled into class bytecode files. You can call each other with Java.

Basic grammar


1. Define functions

Java:

public String retrunStr(String str){
        return str;
}
Copy the code

Kotlin:

fun returnStr(str: String): String {
        return str
}
Copy the code

2. Define variables

Java:

public String str1;
public static final String str2 = "HelloWorld";
Copy the code

Kotlin:

var str1: String? = null
val str2 = "HelloWorld"
Copy the code

3. Vacant judgment:? And!!!!!

Java:

?
public String retrunStr2(String str) {
        if(str ! = null) {return str1;
        } else {
            return ""; }} instead! public void toLowerStr(String str) { try { str.toLowerCase(); } catch (NullPointerException e) { e.printStackTrace(); }}Copy the code

Kotlin:

? fun retrunStr2(str: String?) : String {returnstr ? :""}!!!!! fun toLowerStr(str: String) { str!! .toLowerCase() }Copy the code

4. The for loop

Java:

public void test() {
        List<String> arr = Arrays.asList("java"."kotlin");
        for (int i = 0; i < arr.size(); i++) {
            System.out.println(i);
        }

        for (int i = 0; i < arr.size(); i++) {
            System.out.println(arr.get(i));
        }

        for(Iterator it = arr.iterator(); it.hasNext(); ) { System.out.println(it); }}Copy the code

Kotlin:

fun test() {
        val arr = Arrays.asList("java"."kotlin")
        for (i in arr.indices) {
            println(i)
        }

        for (i in arr.indices) {
            println(arr[i])
        }

        val it = arr.iterator()
        while (it.hasNext()) {
            println(it)
        }

        for(item in arr){
            println(item)
        }
}
Copy the code

5. The when expression

Java:

public void test1() {
        int item = 3;
        switch (item) {
            case 1:
                System.out.println(1);
                break;
            case 2:
                System.out.println(2);
                break;
            case 3:
                System.out.println(3);
                break; default: System.out.println(0); }}Copy the code

Kotlin:

fun test1() {
        val item = 3
        when (item) {
            1 -> println(1)
            2 -> println(2)
            3 -> println(3)
            else -> println(0)
        }
}
Copy the code

Standard functions


1.let

The let extension function is a scope function. When you need to define a variable in a specific scope, you can use the let function.

Object.let {it.todo()// Use it instead of object in the function body to access its public properties and methods}Copy the code
Java example: -- -- -- -- -- -- -- -- -- -- -- -- the public static final void main (@ NotNull String [] args) {Intrinsics. CheckParameterIsNotNull (args,"args");
        String var2 = "testLet"; System.out.println(var2.length()); Int result = 1000; System.out.println(result); // Output 1000} kotlin example: ------------ fun main(args: Array<String>) {val result ="testLet".let {println(it.length) // Output 7 1000 // within the function block can refer to the object by it. } // Return the last line or designation of the function blockreturnExpression. 1000 println(result) // output 1000}Copy the code

2.with

With takes an object as an argument to a function, which can be referred to by this within the function block. Returns the last line of the function block or specifies a return expression.

 with(object){
   //todo
 }
Copy the code
Java example: -- -- -- -- -- -- -- -- -- -- -- -- public final void main (@ NotNull String [] args) {Intrinsics. CheckParameterIsNotNull (args,"args");
        User user = new User("Kotlin", 1, "1111111");
        System.out.println("my name is " + user.getName() + ", I am " + user.getAge() + " years old, my phone number is "+ user.getPhoneNum()); My name is Kotlin, I am 1 years old, my phone number is 1111111 int result = 1000; System.out.println("result: "+ result); } private class User {String name; Integer age; String phoneNum; public User(String name, int age, String phoneNum) { } public StringgetName() {
            return name;
        }

        public Integer getAge() {
            return age;
        }

        public String getPhoneNum() {
            returnphoneNum; }} kotlin example: -- -- -- -- -- -- -- -- -- -- -- -- fun main (args: Array < String >) {val user = user ("Kotlin", 3, "1111111") val result = with(user) {// this means user,this can omit println("my name is $this.name, I am $age years old, my phone number is $phoneNum"My name is Kotlin, I am 1 years old, my phone number is 1111111 1000} // Return the last line of the function block or specifiedreturnExpression. 1000 println("result: $result"} Class User(name: String, age: Int, phoneNum: String) {var name: Stringget() {
                return name
            }
            set(value) {}

        var age: Int
            get() {
                return age
            }
            set(value) {}

        var phoneNum: String
            get() {
                return phoneNum
            }
            set(value) {}
    } 
Copy the code

3.run

The run function is actually a combination of the let and with functions. The run function takes a lambda function as an argument and returns it as a closure. It returns the value of the last line or the specified return expression.

object.run{
	//todo
}
Copy the code
Java example: -- -- -- -- -- -- -- -- -- -- -- -- public final void main (@ NotNull String [] args) {Intrinsics. CheckParameterIsNotNull (args,"args");
        User user = new User("Kotlin", 1, "1111111");
        System.out.println("my name is " + user.getName() + ", I am " + user.getAge() + " years old, my phone number is " + user.getPhoneNum());
        int result = 1000;
        System.out.println("result: "+ result); // Output 1000} kotlin example: ------------ fun main(args: Array<String>) {val user = user ("Kotlin", 1, "1111111") val result = user.run {// this is user,this can be omitted."my name is $this.name, I am $age years old, my phone number is $phoneNum") 1000} // Return the value of the last row or specifiedreturnThe expression 1000 println("result: $result"// output 1000}Copy the code

4.apply

The apply and run functions are similar except that they return different values. Run returns the value of the last line of code as a closure, while apply returns the object itself.

object.apply{
	//todo
}
Copy the code
Public final void main(String[] args) {User User = new User("Kotlin", 1, "1111111");
        String var5 = "my name is " + user.getName() + ", I am " + user.getAge() + " years old, my phone number is " + user.getPhoneNum();
        System.out.println(var5);
        String var3 = "result: "+ user; System.out.println(var3); // Print the user object} kotlin example: ------------ fun main(args: Array<String>) {val user = user ("Kotlin", 1, "1111111") val result = user.apply {// this is user,this can be omitted."my name is $this.name, I am $age years old, my phone number is $phoneNum") 1000} // the apply function returns the object itself user println()"result: $result") // Print the user object}Copy the code

5.also

The structure of the also function is actually very similar to that of the let function. The only difference is the return value. Let returns as a closure, returning the value of the last line in the function, or a default value of type Unit if the last line is null. The also function returns the object itself.

object.also{
	//todo
}
Copy the code
Java example: ------------ public void main(String[] args) {String var1 ="test"; System.out.println(var1.length()); 4 system.out.println (var1); / / outputtest} kotlin example: -- -- -- -- -- -- -- -- -- -- -- -- fun main (args: Array < String >) {val result ="test".also {//it refers to"test"Println (it.length) // Output 4 1000} // Also returns the object itself"test"Println (result) / / outputtest
    }
Copy the code

Function summary: let,with,run,apply,also function distinction

The function name Method of use It, this object The return value Extension function or not Applicable Scenarios
let object.let{ it.xxx } It refers to the current object Return as a closure is This parameter is applicable to scenarios where the value is not null
with with(object){ xxx } This refers to the current object or is omitted Return as a closure no When calling multiple methods of the same class, you can directly call the method of the class, often used in Android RecyclerView onBinderViewHolder, data model attributes mapped to the UI
run object.run{ xxx } This refers to the current object or is omitted Return as a closure is Apply to let,with function any scenario.
apply object.apply{ xxx } This refers to the current object or is omitted Return this is 1. This applies to any scenario in which the run function is used to initialize an instance of an object, manipulate its properties, and eventually return the object.

This is also used when you want to inflate an XML View.

3, generally can be used for multiple extension function chain calls

4. The problem of multi-layer parcel empty judgment processing of data model
also object.also{ xxx } It refers to the current object To return it is Applies to any scenario of a let function, and can generally be used for chained calls to multiple extension functions

  • Reference article: Kotlin series of let, with, run, apply, also function use