Introduction to the

Learn some common Kotlin usages in contrast to Java, followed by training with specific development examples.

object

Java: mainactivity.this

Kotlin writes: this@MainActivity

class

Java: mainactivity.class

Kotlin: MainActivity::class.java

inheritance

Java write:

public class MainActivity extends AppCompatActivity {
}
Copy the code

Kotlin writing:

class MainActivity: AppCompatActivity() {
}
Copy the code

variable

Java write:

Intent intent = new Intent();
Copy the code

Kotlin writing:

Intent intent = Intent();
Copy the code

constant

Java write:

final String text = "text";
Copy the code

Kotlin writing:

var text = "text"
Copy the code

Static constants

Java write:

public class MainActivity extends AppCompatActivity {
	final static String TEXT = "text";
}
Copy the code

Kotlin writing:

const val TEXT = "text"
class MainActivity : AppCompatActivity() {
}
Copy the code

Define methods

Java write

public void method(String message) {
	//body
}
Copy the code

Kotlin writing:

Fun method(message: String) : Unit {//body}Copy the code

Overloaded methods

Java write:

public class MainActiity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceInstance); }}Copy the code

Kotlin writing:

class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState); }}Copy the code

Basic data types

Java write

int i =1; long l = 2; boolean b = true; Double d = 2.0; Float f = 1.0 f; char a = 'a'; String s = "text";Copy the code

Kotlin writing:

Var I: Int = 1 var l: Long = 2 var b: Boolean = true var d: Double = 2.0 var f: Float = 1.0f var a: Char = 'a' var s : // Kotlin provides type inference, Type Optional var I = 1 var L = 2 var b = true var D = 2.0 var f = 1.0 var a = 'a' var s = "text"Copy the code

Comparison of type

Java write:

if ("" instanceOf String) {
}
Copy the code

Kotlin writing

if ("" is String) {
}
Copy the code

Conversion operators

Java write:

int number = 100;
System.out.println(String.format("The number is %d", number);
Copy the code

Kotlin writing:

Var number = 100 println("The number is ${number}")Copy the code

String comparison

Java write

String s1 = "text";
String s2 = "text";
if (s1.equals(s2)) {
	//do something
}
Copy the code

Kotlin writing:

In Kotlin, == compares whether numeric values are equal, whereas === compares whether the addresses of two objects are equal

var s1 = "text"
var s2 = "text"
if (s1 == s2) {
	//do something
}
Copy the code

An array of

Java write

int[] array1 = {1, 2, 3}
float[] array2 = {1f, 2f, 3f}
String[] array3 = {"1", "2", "3"}
Copy the code

Kotlin writing

val array1 = intArrayOf(1, 2, 3)
val array2 = floatArrayOf(1f, 2f, 3f)
val array3 = arrayListOf("1", "2", "3")
Copy the code

cycle

Java write

String[] array = {"1", "2", "3"};
for (int i = 0; i < array.length; i++) {
	System.out.println(array[i]);
}
Copy the code

Kotlin writing

val array = arrayListOf("1", "2", "3"); for (i in array.indices) { println(array[i]}; } for (I in IntRange(1, array.sie-1)) {println(array[I]}; } // 1 for (I in 1.. array.size - 1) { println(array[i]}; 2 for (I in 1 unitl array.size) {println(array[I]}; }Copy the code

Senior cycle

Java write

String[] array = {"1", "2", "3"};
for (String item : array) {
	System.out.println(item);
}
Copy the code

Kotlin writing

var array = arrayListOf("1", "2", "3");
for (item in array) {
	println(item);
}
Copy the code

Judgment is

Java write:

int count = 1;
switch(count) {
    case 0:
        System.out.println(count); 
        break;
    case 1:
    	//fall through
    case 2:
    	System.out.println(count); 
    	break;
    default:
    	System.out.println(count); 
    	break;
}
Copy the code

Kotlin writing:

var count = 1 when(count) { 0 -> { println(count) } int 1.. 2 -> {println(count)} else -> {println(count)}} when(count) {0 -> println(count) int 1.. 2 -> println(count) else -> println(count) }Copy the code

The constructor

Java write

public class MyView extends View { private MyView(Context context) { this(context, null); } public MyView(Context context, @Nullable AttributSet attrs) { this(context, attrs, 0); } public MyView(Context context, @Nullable AttributSet attrs, int defstyleAttr) { super(context, attrs, defStyleAttr); }}Copy the code

Kotlin writing:

class MyView : View { constructor(context: Context) : this(context, null) { } constructor(context : Context, attrs : AttributSet?) : this(context, attrs, 0) { } constructor(context : Context, attrs : AttibuteSet? , defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}} View { constructor(context: Context) : this(context, null) constructor(context : Context, attrs : AttributSet?) : this(context, attrs, 0) constructor(context : Context, attrs : AttibuteSet? , defStyleAttr: Int) : super(context, attrs, defStyleAttr)} class MyView(context: context?) : View { }Copy the code

Class to create

Java write

public class Person {
    String name;
    int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

Person person = new Person("King", 37);
person.setName("James");
person.setAge(38);
System.out.println("name is " + person.getName() + 
        ", age is " + person.getAge());
Copy the code

Kotlin writing

If you don’t want to expose the variable’s set method, you can change var to val

class Person { var name : String? = null get() = field set(value) {field = value} var age : Int = 0 get() = field set(value) {field = value}} Int) var person = Person("King", 37) person.name = "James" person.age = 38 println("name is {$person.name}, age {$person.age}")Copy the code

Privatized set method

Java write

public class Person { String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } private void setName(String name) { this.name = name; } public int getAge() { return age; } private void setAge(int age) { this.age = age; }}Copy the code

Kotlin writing

class Person {
    var name : String ? = null
    private set
    
    var age : Int = 0
    private set
}
Copy the code

Privatized GET method

Java write

public class Person { String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } private String getName() { return name; } private void setName(String name) { this.name = name; } private int getAge() { return age; } private void setAge(int age) { this.age = age; }}Copy the code

Kotlin writing:

class Person {
    private var name : String ? = null
    
    private var age : Int = 0
}
Copy the code

The enumeration

Java write

enum Color {
    RED(0x000), BLUE(0x222)
    Color(int value) {}
}
Copy the code

Kotlin writing

enum class Color (var value: Int) {
    RED(0x000), BLUE(0x222)
}
Copy the code

interface

Java write

public interface Callback {
    void onSuccess();
    void onFail();
}
Copy the code

Kotlin writing

interface Callback {
    fun onSuccess();
    fun onFail();
}
Copy the code

Anonymous inner class

Java write:

new Callback() {
    @Override
    public void onSuccess() {
    }
    
    @Override
    public void onFail() {
    }
}
Copy the code

Kotlin writing:

object:Callback {
    override fun onSuccess() {
    }
    
    override fun onFail() {
    }
}
Copy the code

The inner class

Java write:

public class MainActivity extends AppCompatActivity {
    public class MyInnerClass {
    }
}
Copy the code

Kotlin writing:

class MainActivity : AppCompatActivity {
    inner class MyInnerClass {
    }
}
Copy the code

The inner class accesses a variable of the same name as the outer class

Java write

String name = "king" public class MyInnerClass { String name = "james"; public void test() { System.out.println(name + ", outer name is " + MainActivity.this.name); }}Copy the code

Kotlin writing

var name = "king"

inner class MyInnerClass {
    var name = "james"
    
    fun show() {
        println("name is $name, outer name is ${[email protected]})
    }
}
Copy the code

An abstract class

Java write

public abstract class BaseActivity extends AppCompatActivity implements Runnable {
	abstract void initViews();
}
Copy the code

Kotlin writing

abstract class BaseActivity : AppCompatActivity(), Runnable {
    abstract fun initViews();
}
Copy the code

Static variables and methods

Java write

public class Toastutils { public static Toast sToast; public static void show() { sToast.show(); }}Copy the code

Kotlin writing

Kotlin uses a companion object to carry a static field or static function

companion object ToastUtils { var sToast : Toast ? null fun show() { sToast!! .show() } }Copy the code

Variable parameter

Java write

public init add(int ... array) {
    int count = 0;
    for (int i : array) {
        count += i;
    }
    return count;
}
Copy the code

Kotlin writing

fun add(vararg array: Int) : Int {
    var count = 0;
    array.forEach {
        count += it
    }
    return count
}
Copy the code

The generic

Java write

public class Bean<T extends String> {
    T data;
    public Bean(T t) {
        this.data = t;
    }
}
Bean<String> bean = new Bean<>("123123");
Copy the code

Kotlin writing

class Bean<T : Comparable<String>> (t: T) {var data = T} var bean = bean <String>("123123");Copy the code

The code block

Java write

public class MainActivity extends AppCompatActivity { int number; { number = 1; }}Copy the code

Kotlin writing

class MainActivity : AppCompatActivity() {
    var number = 1
    init {
        number = 1
    }
}
Copy the code

Static code block

Java write

public class MainActivity extends AppCompatActivity { static int number; static { number = 1; }}Copy the code

Kotlin writing

class MainActivity : AppCompatActivity() {
    companion object {
        var number = 0
        init {
            number = 1
        }
    }
}
Copy the code

Method block

Java write

void test(){ { int a = 1; }}Copy the code

Kotlin writing

fun test() {
    run {
        int a = 1
    }
}
Copy the code

Visible modifier

Java write

The modifier scope
public All classes visible
protected Subclasses visible
default Classes under the same package are visible
private Only visible to yourself

Kotlin writing

The modifier scope
public All classes visible
internal As seen under Module
protected Subclasses visible
private Only visible to yourself

Lambda

textView.setOnClickListener(View.OnClickListener {
            fun(v : View) {
                View.GONE.also { v.visibility = it }
            }
        })

textView.setOnClickListener { v -> v.visibility = View.GONE }
Copy the code

The function variables

val result = fun(number1 : Int, number2 : Int) : Int {
	return number1 + number2
}

print(result(1, 2))
Copy the code

Air safety

Types are distinguished between cases where NULL can be used and cases where NULL cannot be used

var string : String = "Kotlin"
string = null //error

var string : String? = "Kotlin"
string = null //ok
Copy the code

Security call

string? .length var len = string? .length ? 1: -Copy the code

!!!!! The operator

The code actively throws a NullPointerException

var len = string!! .lengthCopy the code

When string is null, code execution throws a NullPointerException

Security transformation

var string: String? = "kotlin"
var int: Int? = string as? Int
Copy the code

If string is not an Int, then Int is null

Can be empty collection

If the list contains NULL

val nullableList: List<Int? > = listOf(1, 2, null, 4) val intList : List<Int> = nullableList.filterNotNull()Copy the code

Method supports adding default parameters

Extension methods in Java

public void toast(String text) { toast(this, text, Toast.LENGTH_SHORT); } public void toast(Context context, String text) { toast(context, text, Toast.LENGTH_SHORT); } public void toast(Context context, String text, int time) { Toast.makeText(context, text, time).show(); } "play a toast"; (This, "play a toast ") LENGTH_LONG (this, "play a toast ", toast.length_long);Copy the code

You can define default values for parameters directly on methods in Kotlin

fun toast(context : Context = this, text : String, time : Int = toast.length_short) {toast.maketext (context, text, time).show()} Toast (" play Toast"); (This, "play a toast ") LENGTH_LONG (this, "play a toast ", toast.length_long);Copy the code

Class method extension

Example: Extend the method without changing String

fun String.handle() : String {
    return this + " extension"
}

print("xyz: ".handle())
Copy the code

Extension function

Functions are extended to simplify code generation, including let, with, run, apply, and also

Let the function

Let {it.todo()} // Function 1: use it instead of object to access its public attribute & method Object.let {it.todo()} .todo()}.todo() {var result = null; Int = "king". Let {print(it. Length) 1000} print(result) // use 2 mCanvas? .let { mCanvas.drawCircle() mCanvas.drawLine() }Copy the code

The braking function

Similar to let, except that the return value is:

  • Let function: return value = last line or return expression
  • Also function: Returns the value = itself of the object passed in
Var result: Int = "king". Let {print(it. Length) 1000} Int = "king". Also {print(it. Length) 1000} // result value is string kingCopy the code

With the function

When calling multiple methods/attributes of the same object, you can directly invoke the method name/attribute without the object name duplication

var p = Person("king", 17)
with(p) {
    print("name is $name, age os $age")
}
Copy the code

The run function

Combined with the functions of let and with, namely:

  • When calling multiple methods/attributes of the same object, you can directly invoke the method name/attribute without the object name duplication
  • Defines a variable in a particular scope
  • Do a unified short processing
p? .run { print("name is $name, age os $age") }Copy the code

The apply function

This is similar to the run function, except that the return value is:

  • The run function returns the value/expression of the last line
  • The apply function returns the object itself passed in
var result1 = p.run { print("name is $name, Age OS $age") 1024} var result2 = p.ply {print("name is $name, age OS $age") 1024} // Result2 is the P objectCopy the code