This section focuses on the built-in types and simple usage of Kotlin

Declaration of variables

Val b: String = "Hello Kotlin" copy codeCopy the code

Kotlin’s variable declaration, somewhat similar to TypeScript, is a more modern form of modifier variable names: type = value, where the type declaration can be omitted.

There are two kinds of modifiers

  • Val: read-only variable
  • Var: reads and writes variables. The value must be specified and cannot be changed

Compared with the Java

int a = 2; final String b = "Hello Java"; Copy the codeCopy the code
Var a = 2 val b = "Hello Kotlin" copy codeCopy the code

Confusing Long type tag

In Java, Long terminations with l can be compiled, but not recommended (lowercase L, which looks like the number 1).

long c = 1234567890l; // ok but not good. long d = 1234567890L; // ok copy codeCopy the code

In Kotlin, the compiler fails directly, forcing it to change to L

Val c = 1234567890l // compile error. val d = 1234567890l // okCopy the code

Kotlin numeric type conversion

In Java, int can be implicitly converted to long

int e = 10; long f = e; // implicit conversion duplicates codeCopy the code

And then Kotlin, sorry, doesn’t support it

Val E: Int = 10 val F: Long = e // implicitness not allowed val F: Long = e.T Long() // OK Copy codeCopy the code

Unsigned type (compatible with C Native)

As of V1.3, Kotlin supports unsigned types

String definition

Take a look at Kotlin’s code for defining HTML strings

val n = """ <! doctype html> <html> <head> <meta charset="UTF-8"/> <title>Hello World</title> </head> <body> <div id="container"> <H1>Hello World</H1> <p>This is a demo page.</p> </div> </body> </ HTML > "". TrimIndent () println(n) Copy codeCopy the code

Compared to Java, it is so simple that using a Java definition of a piece of code that behaves the same way, a bunch of newlines, looks like a big head

Kotlin string

String comparison

  • a == b: compares content, equivalent to Javaequals
  • a === b: Compares whether the object is the same object

String template

  • “$name” =>” $name”

An array of

Kotlin Java
The integer IntArray int[]
Plastic packing Array Integer[]
character CharArray char[]
Characters of the packing Array Character[]
string Array String[]

Array creation

int[] c = new int[]{1, 2, 3, 4, 5}; Copy the codeCopy the code

In Kotlin, arrays are created in the following way

Val c0 = intArrayOf(1, 2, 3, 4, 5) val c1 = IntArray(5){it + 1} copy codeCopy the code

Array length

Java

int[] a = new int[5]; System.out.println(a.length); // only array uses 'length' to copy codeCopy the code

Kotlin

Val a = IntArray(5) println(a.size) // same with the Collections(e.g. ListCopy the code

Reading and writing arrays

Java

String[] d = new String[]{"Hello", "World"}; d[1] = "Java"; System.out.println(d[0] + ", " + d[1]); Copy the codeCopy the code

Kotlin

Val d = arrayOf (" Hello ", "World") d [1] = "Kotlin println (" ${d [0]}, ${d [1]}") to copy codeCopy the code

Array traversal

Java

float[] e = new float[]{1, 3, 5, 7}; for(float element : e) { System.out.println(element); } Duplicate codeCopy the code

Kotlin, it’s kind of like the element traversal in Python

Val e = floatArrayOf(1f, 3f, 5f, 7f) for (element in e) {println(element)} copies the codeCopy the code

Alternatively, you can use forEach higher-order functions

E.freach {element -> println(element)} copies the codeCopy the code

The containment relationship of an array

Java

for(float element : e) { if(element == 1f) { System.out.println("1f exists in variable 'e'"); break; }} Copy the codeCopy the code

In Kotlin, simple doesn’t work

If (1f in e) {println("1f exists in variable 'e'")} copies the codeCopy the code

interval

It doesn’t exist in Java, so let’s just look at Kotlin’s notation

Interval creation

Closed interval (..)

val intRange = 1.. 10 // [1,10] val charRange = 'a'.. 'z' val longRange = 1L.. 100L copy codeCopy the code

Open and close interval, before closed and then open (until)

Val intRangeExclusive = 1 until 10 // [1,10) val charRangeExclusive = 'A' until 'z' val longRangeExclusive = 1L until 100L copy codeCopy the code

Backward order interval (downTo)

Val intRangeReverse = 10 downTo 1 // [10,9...,1] Val charRangeReverse = 'z' downTo 'a' val longRangeReverse = 100L DownTo 1L copies codeCopy the code

Interval step (step)

When defining the interval, we can also define the step size, which is 1 by default

val intRangeWithStep = 1.. 10 step 2 // [1, 3, 5, 7, 9] val charRange = 'a'.. 'z' step 2 val longRange = 1L.. 100L step 5 Copy the codeCopy the code

Interval iteration

Interval iterations are basically similar to arrays

For (element in intRange) {println(element)} intRange. ForEach {println(it)} // The default argument for higher-order functions is called it copy codeCopy the code

The inclusion relation of intervals

if(3 in intRange) { println("3 in range 'intRange'") } if(12 ! In intRange) {println("12 not in range 'intRange'")Copy the code

Interval application

Val Array = intArrayOf(1, 3, 5, 7) for(I in array.indices) {println(array[I])Copy the code

Array. indices returns the range of array indexes

Collections framework

Kotlin has made some enhancements to Java collections, as shown in the following

  • Added an interface to the immutable collection framework
  • Not reinvent the hatchback and reuse all implementation types of the Java Api
  • Provides rich medical methods, such asforEach/map/flatMapEtc.

Scala is also a JVM language, and Kotlin references Scala for many of its features

Collection framework interface type comparison

Kotlin Java
Immutable List List List
The variable List MutableList List
Immutable Map Map<K, V> Map<K, V>
Variable Map MutableMap<K, V> Map<K, V>
Immutable Set Set Set
Variable Set MutableSet Set

Creation of a collection framework

Java

List<Integer> intList = new ArrayList<>(Arrays.asList(1, 2, 3)); Copy the codeCopy the code

Kotlin

Val intList: List<Int> = listOf(1, 2, 3) MutableList<Int> = mutableListOf(1, 2, 3) Map<String, Any> = mapOf("name" to "benny", "age" to 20) val map2: Map<String, Any> = mutableMapOf("name" to "benny", "age" to 20Copy the code

Collection enables class reuse and type aliasing

Let’s compare Java to Kotlin’s code for creating collections, Java

List<String> stringList = new ArrayList<>(); // java.util.ArrayList copies the codeCopy the code

Kotlin

Val stringList = ArrayList < String > () / / kotlin collections. The ArrayList duplicate codeCopy the code

The type alias definition for the collection in Kotlin

@sincekotlin ("1.1") public Actual TypeAlias ArrayList<E> = java.util.ArrayList<E> @sincekotlin ("1.1") public Actual TypeAlias ArrayList<E> = java.util Typealias LinkedHashMap<K, V> = java.util.LinkedHashMap<K, V> @sinceKotlin ("1.1") public Actual TypeAlias HashMap<K, V> = java.util.HashMap<K, V> @sinceKotlin ("1.1") public Actual TypeAlias LinkedHashSet<E> = java.util.LinkedHashSet<E> @sinceKotlin ("1.1") public Actual TypeAlias HashSet<E> = java.util.HashSet<E> Copy codeCopy the code

Kotlin uses type aliases for cross-platform purposes. Kotlin doesn’t just want the same code to run on the JVM, it can also run on Native platforms, so maybe one day Kotlin will compile binary machine code instead of Java bytecode!

Read and write to the collection framework

Kotlin also supports operator overloading

Add elements

Java

for(int i = 0; i < 10; i++) { stringList.add("num: " + i); } Duplicate codeCopy the code

Kotlin

for(i in 0.. 10) {stringList += "num: $I"Copy the code

Remove elements

Java

for(int i = 0; i < 10; i++) { stringList.remove("num: " + i); } Duplicate codeCopy the code

Kotlin

for(i in 0.. 10) {stringList -= "num: $I"Copy the code

Modify the element

Java

stringList.set(5, "HelloWorld"); String valueAt5 = stringList.get(5); Copy the codeCopy the code

Kotlin

StringList [5] = "HelloWorld" val valueAt5 = stringList[5] copy codeCopy the code

If it is Map Java

HashMap<String, Integer> map = new HashMap<>(); map.put("Hello", 10); System.out.println(map.get("Hello")); Copy the codeCopy the code

Kotlin

Val map = HashMap<String, Int>() map["Hello"] = 10 println(map["Hello"]) copy codeCopy the code

Several important data structures

Pair

You can think of it as a key-value pair, a data structure containing the first and second fields

val pair = "Hello" to "Kotlin" val pair2 = Pair("Hello", First val second = pair.second val (x, y) = pairCopy the code

Triple

Similar to Pair, but with three values

val triple = Triple("x", 2, Second = triple. Second val third = triple. Third val (x, y, x) Z) = triple // Destruct expression copy codeCopy the code

function

In Kotlin, functions are also types, first-class citizens that can be assigned, passed, and called when appropriate

Learning roadmap

Definition of a function

A function contains: function name, function argument list, function return value, function body

Fun main(args: Array<String>):Unit {println(args.contentToString())} Copy codeCopy the code

Function VS method

  • Methods can be thought of as a special type of function
  • Formally, there arereceiverThe function of is a method

Type of function

In Kotlin, functions are also typed

fun foo() { } // () -> Unit fun foo(p(): Int): String { ... } // (Int) -> String class Foo { fun bar(p0: String, p1: Long): Any { ... } // Foo.(String, Long) -> Any, where Foo is the receiver of the bar method, type equivalent to (Foo, String, Long) -> Any} copy codeCopy the code

Function reference

Function references are similar to function Pointers in C and can be used for function passing

fun foo() { } // val f: () -> Unit = ::foo fun foo(p(): Int): String { ... } // val g: (Int) -> String = ::foo class Foo { fun bar(p0: String, p1: Long): Any { ... } // val h: (Foo, String, Long) -> Any = Foo::bar} copy codeCopy the code

Bind the function reference of receiver

val foo = Foo() val m: (String, Long) -> Any = foo::bar // Bind a function reference to receiver, where foo is an object instance f(r, x, y) = r * (x + y) // make: R = 2 m(x, y) = f(2, x, y) = 2 times (x + y) copy the codeCopy the code

Variable length parameter (varargKeywords)

Fun main(vararg args: String) {println(args.contentToString())} Copies the codeCopy the code

The return value more

Pair or Triple defines the return value, using the structure to get the return value

fun multiReturnValues(): Triple<Int, Long, Double> {return Triple(1, 3L, 4.0)} val (a, b, c) = multiReturnValues(Copy the code

The default parameters

Kotlin allows you to specify default values for parameters, so you don’t have to define method overloads as Java does

Fun defaultParameter(x: Int, y: String, z: Long = 0L) {TODO()} defaultParameter(5, "Hello") // here z uses the default 0L copy codeCopy the code

A named function

fun defaultParameter(x: Int = 5, y: String, z: Long = 0L) {// Not the last TODO()} defaultParameter(y = "Hello") // Pass y only, use the default values for the restCopy the code