The author | HuoBingGan edit | fan deer

preface

As experienced programmers who have mastered one or more languages, we often get questions like “How do you say ‘goodbye’ in Japanese?” “, “How do you say ‘hello’ in Spanish? So I decided to list out some common syntax comparisons that will make getting started with Kotlin very easy if you are familiar with Java.

This article is written primarily for Java programmers who need to get up and running with Kotlin, who are focused on how Kotlin can write something like Java, so there is little to cover Kotlin’s advanced features.

1. How to define variables

Java defines variables as follows:

String string = "Hello";
Copy the code

The basically equivalent Kotlin definition variable is written as follows:

var string: String = "Hello"
Copy the code

Java defines final variables as follows:

final String string = "Hello";
Copy the code

Note that the preceding is a compile-time constant, which Kotlin would write like this:

const val string: String = "Hello"
Copy the code

Also final variable, Java writes:

final String string = getString();
Copy the code

Note that this is not a compile-time constant, Kotlin writes:

val string: String = getString()
Copy the code

In addition, Kotlin has type derivation, so the above variable definitions can mostly omit the type String.

2. How to define a function

How to define functions, or methods, in Java needs to be defined in a class:

public boolean testString(String name){
    ...
}
Copy the code

Equivalent Kotlin:

fun testString(name: String): Boolean {
    ...
}
Copy the code

Notice that the return value is placed after the parameter.

3. How to define static variables and methods

Java static methods or variables simply add static:

public class Singleton{
    private static Singleton instance = ...;

    public static Singleton getInstance(){
        ...
        return instance;
    }
}
Copy the code

Kotlin’s literal translation is:

class KotlinSingleton{
    companion object{
        private val kotlinSingleton = KotlinSingleton()

        @JvmStatic
        fun getInstance() = kotlinSingleton

    }
}
Copy the code

Notice how getInstance is written. The JvmStatic annotation compiles the getInstance method to the same signature as Java’s static methods. Without the JvmStatic annotation, the method cannot be called in Java in the same way as Java’s static methods.

In addition, for static method and variable scenarios, package-level functions are recommended in Kotlin.

4. How to define an array

Java arrays are very simple and somewhat abstract, as they are compile-time generated classes:

String[] names = new String[]{"Kyo", "Ryu", "Iory"};
String[] emptyStrings = new String[10];
Copy the code

Kotlin’s array is actually a little more realistic and looks a little easier to understand:

val names: Array<String> = arrayOf("Kyo", "Ryu", "Iory") val emptyStrings: Array<String? > = arrayOfNulls(10)Copy the code

Notice that Array

T is the type of the Array element. In addition, the String? Represents a String that can be null.

The use of arrays is basically the same. Note that to avoid the overhead of boxing and unboxing, Kotlin provides a custom array type written XArray for basic types such as Int, Short, Byte, Long, Float, Double, Char, and so on. For example, the custom array of Int is IntArray. If we wanted to define an array of integers, we would write it as follows:

val ints = intArrayOf(1, 3, 5)
Copy the code

5. How to write variable length parameters

Java variable length arguments are written as follows:

void hello(String... names){
    ...
}
Copy the code

Kotlin’s variable length parameter is written as follows:

fun hello(vararg names: String){

}
Copy the code

6. How to write a ternary operator

Java can write ternary operators:

int code = isSuccessfully? 200-400;Copy the code

A lot of people complain about why Kotlin doesn’t have this operator… This is said to be because Kotlin uses a much more complex scenario than Java, so adding this ternary operator will cause more trouble for the syntax parser, and Scala is similar. So in this case, how do we write Kotlin?

int code = if(isSuccessfully) 200 else 400
Copy the code

Note that statements like if else are also expressions, unlike Java.

7. How to write main

There is only one way to write Java:

class Main{ public static void main(String... args){ ... }}Copy the code

Notice that arguments can be variable-length arguments or arrays, either of which can work.

For Kotlin, the main function is written as follows:

class KotlinMain{
    companion object{
        @JvmStatic
        fun main(args: Array<String>) {

        }
    }
}
Copy the code

Kotlin can have package-level functions, so we don’t need to declare a class to wrap the main function:

fun main(args: Array<String>){
    ...
}
Copy the code

8. How do I instantiate a class

Languages such as Java and C++ often use the new keyword when constructing objects, such as:

Date date = new Date();
Copy the code

Kotlin does not need the new keyword when constructing objects, so this is equivalent to:

val date = Date()
Copy the code

9. How to write Getter and Setter methods

Java getters and setters are conventions, not syntactic features, so they can be defined relatively freely:

public class GetterAndSetter{ private int x = 0; public int getX() { return x; } public void setX(int x) { this.x = x; }}Copy the code

Kotlin has attributes:

class KotlinGetterAndSetter{
    var x: Int = 0
        set(value) { field = value }
        get() = field
}
Copy the code

Notice that we’ve explicitly defined the getter and setter for x, and field is the real variable behind x, so in the setter we’re actually assigning a value to field, and the getter is returning field. If you want to control access to x, you can use custom getters and setters to do so:

class KotlinGetterAndSetter{ var x: Int = 0 set(value) { val date = Calendar.getInstance().apply { set(2017, 2, 15)} if(system.currentTimemillis () < date.timeinmillis){println("Cannot be set before 2017.3.18")}else{field = value  } } get(){ println("Get field x: $field") return field } }Copy the code

10. How do I delay initialization of a member variable

If a java-defined class member variable is not initialized, the primitive type is initialized to its default value. For example, int is initialized to 0, Boolean is initialized to false, and members of non-primitive types are initialized to NULL.

public class Hello{
    private String name;
}
Copy the code

Similar code in Kotlin literally translates as:

class Hello{
    private var name: String? = null
}
Copy the code

The side effect of using nullable types is that every time you want to use name, you need to check if it is null. If you do not use controllable types, add the lateinit keyword:

class Hello{
    private lateinit var name: String
}
Copy the code

Lateinit is used to tell the compiler that the name variable will be taken care of later.

For final member variables, Java requires that they be initialized ina constructor or constructor block:

public class Hello{
    private final String name = "Peter";
}
Copy the code

That is, if I want to define a final variable that can be deferred until a certain point is actually used and initialized, I can’t do that in Java.

Kotlin’s solution is to use lazy as a delegate:

class Hello{
    private val name by lazy{
        NameProvider.getName() 
    }
}
Copy the code

Only when the name attribute is used will the Lambda after lazy be executed and the value of name be computed.

11. How do I get an instance of class

In Java:

public class Hello{ ... }... Class<? > clazz = Hello.class; Hello hello = new Hello(); Class<? > clazz2 = hello.getClass();Copy the code

We’ve shown you two ways to get a class, either by the name of the class or by the instance of the class. When I first came to Kotlin, the way to get a Java Class was confusing.

class Hello

val clazz = Hello::class.java

val hello = Hello()
val clazz2 = hello.javaClass
Copy the code

The Kotlin code with the same effect looks really strange. In fact, Hello::class gets Kotlin’s KClass, which is Kotlin’s type. If you want to get a Java class instance, you need to use the previous method.