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

Declaration of variables

val b: String = "Hello Kotlin"
Copy 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 code
var a = 2
val b = "Hello Kotlin"
Copy 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 the code

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

val c = 1234567890l // compile error.
val d = 1234567890L // ok
Copy the code

Kotlin numeric type conversion

In Java, int can be implicitly converted to long

int e = 10;
long f = e; // implicit conversion
Copy 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.toLong() // ok
Copy 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 = "" "
         
       Hello World   
      

Hello World

This is a demo page.

"""
.trimIndent() println(n) Copy 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 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 the code

Array length

Java

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

Kotlin

val a = IntArray(5)
println(a.size) // same with the Collections(e.g. List)
Copy 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 code

Kotlin

val d = arrayOf("Hello"."World")
d[1] = "Kotlin"
println("${d[0]}.${d[1]}")
Copy the code

Array traversal

Java

float[] e = new float[] {1.3.5.7};
for(float element : e) {
  System.out.println(element);
}
Copy 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)
}
Copy the code

Alternatively, you can use forEach higher-order functions

e.forEach { element -> println(element) }
Copy 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 code

In Kotlin, simple doesn’t work

if(1f in e) {
  println("1f exists in variable 'e'")}Copy 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 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 the code

Backward order interval (downTo)

val intRangeReverse = 10 downTo 1 / / [10, 9,..., 1]
val charRangeReverse = 'z' downTo 'a'
val longRangeReverse = 100L downTo 1L
Copy 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 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 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 code

Kotlin

val intList: List<Int> = listOf(1.2.3) // Elements cannot be added or removed
val intList2: MutableList<Int> = mutableListOf(1.2.3) // Elements can be added or removed

val map: Map<String, Any> = mapOf("name" to "benny"."age" to 20)
val map2: Map<String, Any> = mutableMapOf("name" to "benny"."age" to 20) // where "name" to "benny" is an infix expression
Copy 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
Copy the code

Kotlin

val stringList = ArrayList<String>() // kotlin.collections.ArrayList
Copy 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 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 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);
}
Copy 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);
}
Copy 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 code

Kotlin

stringList[5] = "HelloWorld"
val valueAt5 = stringList[5]
Copy 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 code

Kotlin

val map = HashMap<String, Int>()
map["Hello"] = 10
println(map["Hello"])
Copy 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"."Kotlin") // Two creation modes
val first = pair.first // Get the corresponding element
val second = pair.second
val (x, y) = pair // Destruct the expression
Copy the code

Triple

Similar to Pair, but with three values

val triple = Triple("x".2.3.0)
val first = triple.first // Get the corresponding element
val second = triple.second
val third = triple.third
val (x, y, z) = triple // Destruct the expression
Copy 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 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(a){}// () -> 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 for the bar method and is of type (Foo, String, Long) -> Any
}
Copy the code

Function reference

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

fun foo(a){}// 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 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 * (x + y)
Copy the code

Variable length parameter (varargKeywords)

fun main(vararg args: String) {
  println(args.contentToString())
}
Copy the code

The return value more

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

fun multiReturnValues(a): Triple<Int.Long.Double> {
  return Triple(1.3L.4.0)}val (a, b, c) = multiReturnValues() // Destruct the return value
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") // the default z is 0L
Copy the code

A named function

fun defaultParameter(x: Int = 5, y: String, z: Long = 0L) { // Not the final argument
  TODO()
}

defaultParameter(y = "Hello") // Pass only the y argument and use the default values for the rest
Copy the code