First line of code Kotlin learning notes

Keywords: kotlin

Programming languages are divided into compiled languages and interpreted languages. Compiled languages are characterized by compiling source code into binary files at one time and then executing directly; Interpretative languages have an interpreter that interprets the source code into binary data at run time and then executes it. Therefore, interpretative languages are less efficient. Java needs to parse the generated class file through the parser, so the Java language is also an interpreted language.

  • Kotlin is 100% compatible with Java because it compiles kotlin files into class files of the same specification through kotlin's own compiler, so it can also be recognized by the JVM.

  • A web site where Kotlin runs online:

Variables and functions


  • val (short for value) declares an immutable variable. Corresponding to the final variable in Java
  • Var (short for variable) declares a variable, corresponding to a non final variable in Java


fun largerNum(num1: Int, num2: Int): Int {
    return max(num1, num2)

Where fun is the abbreviation of function, which defines the keyword of the function. In parentheses are the incoming parameters. The parameter declaration method is "parameter name: parameter type". In the back: Int indicates that the data of Int type is returned at the end of function execution, and in braces is the function body. When there is only one line of code in the function, kotlin allows you to use the following equivalent effect instead of writing the function body:

fun largerNum2(num1: Int, num2: Int): Int = max(num1, num2)

logical control

  • if and when

Compared with the if keyword in Java, if in kotlin has an additional function. It can return values, such as:

fun largeNum3(num1: Int, num2: Int) = if (num1 > num2) num1 else num2

When statement allows you to pass in a parameter of any type, and then you can define a series of conditions in the structure of when. The format is:
The matching value - > {execution logic}. When there is only one line of code, {} can be omitted.

fun checkNum(num: Number) {
    when (num) {
        is Int -> print("num is Int")
        is Double -> print("num is Double")
        else -> print("number not support")

The is keyword is the key to type matching, which is equivalent to the instanceof keyword in Java.

Circular statement

  • Use... To represent the interval. For example, 0... 10 represents the interval of [0,10], such as var range=0... 10
fun loopNum() {
    for (i in 0..10) {

If it is a left closed and right open interval, it is val range=0 until 10, indicating that the interval is [0,10]; if you want to skip some elements, you can use the step keyword:

fun jumpNum() {
    for (i in 0 until 10 step 2) {

Indicates that the execution interval is incremented by 2, and the output results are 0, 2, 4, 6 and 8

The above are in ascending order. If descending order is required, use downTo

Inheritance and constructor

  • Declaration class
class Person {
   var name = ""
   var age = 0

   fun eat() {
       print("$name is eating, He is $age years old")

Instantiation class var p = Person()

  • inherit
    By default, classes in kotlin cannot be inherited, which is equivalent to adding the final keyword to the class in Java. If you want the class to be inherited, add the open keyword in front of the class, as follows:
open class Person {

Subclass to inherit the Person class:

class Student : Person() {
    var sno = ""
    var grade = 0
  • Primary constructor & secondary constructor
class Student(val sno: String, var grade: Int, name: String, age: Int) : Person() {

    constructor(name: String, age: Int) : this("", 0, name, age)

    constructor() : this("", 0)

Constructor declares a secondary constructor. If there is no primary constructor, there is no need to add parentheses when inheriting the Person class, such as:

class Student : Person {
    constructor(name: String, age: Int) : super(name, age)
  • Interface
interface Study {
    fun readBooks()
    fun doHomeWork();

The declared interface method can have its own implementation. Student implements the Study interface:

class Student : Person, Study {
    constructor(name: String, age: Int) : super(name, age)

    override fun readBooks() {

    override fun doHomeWork() {
  • Data class & singleton

Data class: the data keyword is declared in front of the class, indicating that it is a data type. There is no need to rewrite the methods such as equals(), hashCode(), toString(), etc.

data class CellPhone(var brand: String, val price: Double) {

Singleton: add an object before the class (there is no class keyword), which means it is a singleton

object SingleTon {
    fun singletonTest() {
        print("singletonTest is called")

When using: SingleTon.singletonTest(), which is similar to the static call in Java, kotlin helps us create an instance of SingleTon and ensures that there will only be one SingleTon instance in the world.

Lambda programming

  • A collection is created in traversal

Set: mainly the creation and use of List, set and Map

List can be created in the following ways:

1,var list = listOf("Apple", "Banana")
Note: the set created by listOf is immutable. How to create subsequent sets that are mutableListOf():

val list = mutableListOf("Apple", "Banana")

2. Similar to the writing method in Java:

val list = ArrayList<String>()

The creation of Set is basically the same as that of List, except that the keyword is replaced with setOf and mutableSetOf

How to create a Map:
1. It is similar to writing and in Java

val map = HashMap<String, Int>()
map.put("apple", 1)


val map = HashMap<String, Int>()
map["apple"] = 1

3. Create with mapOf, mutableMapOf

val map = mapOf("apple" to 1, "pear" to 2)
for ((fruit, number) in map) {
    print("fruit is $fruit,number is $number")
  • Collection's functional API

Syntax structure of Lambda expression:
{parameter name 1: parameter type, parameter name 2: parameter type - > function body}

val maxLength = list.maxBy({ fruit: String -> fruit.length })

When the Lambda parameter is the last parameter of the function, you can move the Lambda expression to the outside of the function bracket, which will become as follows:

val maxLength = list.maxBy() { fruit: String -> fruit.length }

When the Lambda parameter is the only parameter of the function, you can also omit the parentheses of the function:

val maxLength = list.maxBy{ fruit: String -> fruit.length }

Continue, when there is only one parameter in the Lambda parameter list, you do not need to declare the parameter name, but you can use the it keyword instead, which becomes:

val maxLenght = list.maxBy { it.length }

map function: maps each element in the collection to another value
Filter function: used to filter the data in the collection
Any and all functions: any is used to judge that at least one element in the set meets the specified conditions, and all is used to judge that all elements meet the specified conditions.

Null pointer check

  • The default types are all non nullable types. If the type is nullable, it will be followed by?, such as Int, which represents an nullable integer; String represents a non nullable String, and String represents an nullable String.

  • Auxiliary tools for air judgment:
    ?. Means to call normally when the object is not empty, and do nothing when the object is empty
    ?: indicates that both the left and right sides of the operator receive an expression. If the result of the expression on the left is not empty, the result of the expression on the left is returned; otherwise, the result of the expression on the right is returned.

It can be judged by combining?. and?: for example:

fun getTextLength(text: String?) = text?.length ?: 0

!! Means to use assertions to make sure that the object will not be empty. This is generally not recommended

Let refers to a function that calls itself, and can be combined with?. and let to optimize the empty judgment code, such as:

fun executeFun(stu: Study?) {
    stu?.let {

Posted by songwind on Sun, 24 Oct 2021 06:34:03 -0700