The basic syntax and types of Kotlin

Posted by NotVeryTechie on Fri, 01 May 2020 00:10:34 +0200

Basic types

Basic types used in Kotlin: numbers, characters, Booleans, arrays, and strings.

number

Type Bit
Double 64
loat 32
Long 64
Int 32
Short 16
Byte 8

Representation

In Kotlin, the values can be expressed literally as follows:

  • Decimal: 123
    Long type is marked with capital L: 123L
  • Hex: 0x0F
  • Binary: 0b0000111

As of 1.1, you can use underscores to make numeric constants easier to read:

val oneMillion = 1_000_000                         => 100000
val creditCardNumber = 1234_5678L                  => 12345678
val socialSecurityNumber = 999_99_9999L            => 999999999
val hexBytes = 0xFF_EC_DE_5E                       => 4293713502
val bytes = 0b11010010_01101001_10010100_10010010  =>3530134674

Type conversion

There are two types of conversion:
-Implicit conversion

val a: Int? = 1 // A boxed Int (java.lang.Integer)
val b: Long? = a // Implicit transformation produces a boxed Long (java.lang.Long)
Log.d("",a == b+"") => false 
Long's equals() detects that other parts are also long, and smaller types cannot be implicitly converted to larger types. -Explicit conversion
val b: Byte = 1 // OK, the literal value is statically detected
val i: Int = b // Error will be reported here. Compilation fails

//Explicit conversion
val i: Int = b.toInt()

The basic conversion is as follows:

  • toByte(): Byte
  • toShort(): Short
  • toInt(): Int
  • toLong(): Long
  • toFloat(): Float
  • toDouble(): Double
  • toChar(): Char

Basic grammar

Defining functions

//Function = > Android method
//Basic function Unit means that meaningless return is optional
fun sum():Unit{
    .....
}
//Functions with parameters
fun sum(a: Int, b: Int){
    .....
}
//Function with return value
fun sum(): Int{
    return 0
}
//Expression as function body
fun sum(a: Int, b: Int) = a + b

Defining variables

//Basic method of defining variables: var variable name: variable type = initial value of variable

/******************Variable variable*******************/
var a: Int = 1  // Assign now
val c: Int  // If there is no initial value, the type cannot be omitted
c = 3       // definitely assigned 

//After type +? Means it can be empty
var name: String? = null;

//lateinit delay loading can only define non initialization globally
lateinit var sex: String;

//When automatically infer type definition, direct assignment can automatically infer type
var a = 2

/******************Read only variable*******************/
val PI = 3.14

/*****************Array***********************/
//Instantiate an array with a length of 3 and a value of 1 2 3
var sz: Array<String> = Array(3, { i -> (i +1).toString() })

/*****************Set***********************/
val items = listOf(1, 2, 3, 4)
Note: var and val are used to define variables in Kotlin. Val means read-only, which is equivalent to Android final

Use string template

var a = 1
// Simple name in template:
val s1 = "a is $a"  => "a is 1"

var b = 2
// Any expression in the template:
val s2 = "${s1.replace("is", "was")}, but now is $b"  => a was 1,but now is 2

if conditional expression

fun maxOf(a: Int, b: Int): Int {
    if (a > b)
        return a
    else 
        return b
}

fun main(args: Array<String>) {
    Log.d("","max of 0 and 42 is ${maxOf(0, 42)}") => max of 0 and 42 is 42
}

Use nullable value and null detection

fun parseInt(str: String): Int? {
    return str.toIntOrNull()
}
var age = "10";
var name = "Ez"

val x = parseInt(age)  => 10
val y = parseInt(name) => null Empty object

for loop

//  item Item cycle
val items = listOf("apple", "banana", "kiwi")
for (item in items) {
    Log.d("",item)    => apple  banana  kiwi
}
//Subscript cycle
val items = listOf("apple", "banana", "kiwi")
for (index in items.indices) {
    Log.d("","$index is ${items[index]}")  
}
=>  0 is apple
    1 is banana
    2 is kiwi

when expression

val items = listOf("apple", "banana", "kiwi")
for (item in items) {
    when (item) {
        "apple" ->{
             Log.d("==", "apple")
        }
        "banana" -> Log.d("==", "banana")
        else -> {
            Log.d("==", "kiwi")
        }
    }
}
Note: when is the switch operator, you can use block {}, or you can execute it directly.

Section

val x = 10
val y = 9
if (x in 1..y+1) {
   //x stay1reach10Including1and10
}
if (x !in 1..y+1) {
   //x Be not in1reach10Including1and10
}


//Interval iteration
 for (x in 1..5) {
         Log.d("==", "x")  => 1 2 3 4 5
    }

//Sequence iteration
for (x in 1..10 step 2) {
        Log.d("==", "x")  => 1 3 5 7 9
    }
for (x in 9 downTo 0 step 3) {
        Log.d("==", "x")  => 9 6 3 0
    }

Use lambda expressions to filter and map collections

val fruits = listOf("banana", "avocado", "apple", "kiwi")
fruits.filter { it.startsWith("a") }  //The initial is"a"
      .sortedBy { it }
      .map { it.toUpperCase() }       //Capitalization
      .forEach {  Log.d("===",it) }   =>APPLE  AVOCADO
lambda expressions and higher-order functions can be viewed on [official website] (https://www.kotlincn.net/docs/reference/lambdas.html)

Create a base class and its instances

val rectangle = Rectangle(5.0, 2.0) // 'new' keyword is not required

At the beginning, I was not used to it, but the code was very simple. I felt that the writing method was very similar to that of the front end. Generally speaking, it was very easy to use.

Topics: Java Android Lambda