Kotlin Tutorial for Android Developers (3)

I. Introduction

In a Kotlin tutorial Android developers (b) , we talked about the essential foundation Kotlin, namely Kotlin in the basic data types , arrays , and collection of the three knowledge points.

In this section, let's talk about the two knowledge points of methods in Kotlin and Lambda expressions .

Second, the Kotlin method

Objects are the most important in Java, and methods are the most important in Kotlin. In Kotlin, methods can be directly defined in files, and do not necessarily need to be defined in classes.

2.1, method declaration

The basic format of a method in Kotlin is as follows:
Method format

Specific code implementation

fun plus(a: Int, b: Int): Int {
    
    
    return a + b
}

2.1.1, class member methods

How to write the member methods of a class

class Person {
    
    
   	// 成员方法
    fun test1() {
    
    
        println("成员方法")
    }
}

How to call member methods

fun main() {
    
    
    Person().test1()
}

2.1.2, class method (static method)

There is no static keyword in Kotlin, but we can use the companion object (Kotlin's companion object) to achieve the purpose of the class method.

How to write static methods

class Person {
    
    
    companion object {
    
    
        fun test2() {
    
    
            println("companion object 实现类方法")
        }
    }
}

Static method call

 Person.test2()

2.1.3, static class

In Kotlin, if we want to implement a tool class util, we can use object to create a static class. The methods in the static class are all static methods.

How to write static classes

object NumUtil {
    
    
    fun double(num: Int): Int {
    
    
        return num * 2
    }
}

Invocation of methods in static classes

println("umUtil.double(2): ${NumUtil.double(2)}")

2.1.4, single expression method

When the method returns a single expression, you can omit the curly braces and specify the code body after the = sign.

Single expression method

fun double(x: Int): Int = x * 2

2.2. Method parameters

2.2.1, default parameters

In Kotlin, you can set some default parameters for the method, and use the default parameter values ​​when the corresponding parameters are omitted. Compared with Java, this can reduce the number of overloads.

Default parameter writing

// off 的默认值就是 0, len 的默认值就是 b.size
fun read(b: Array<Byte>, off: Int = 0, len: Int = b.size) {
    
    

}

2.2.2, variable number of parameters

In Java, use... (such as String...) to set variable type parameters. In Kotlin, vararg modifiers are used to mark parameters to achieve variable parameters.

Variable parameter writing

// 通过 vararg 修饰
fun append(vararg str: Char): String {
    
    
    val result = StringBuffer()
    for (char in str) {
    
    
        result.append(char)
    }

    return result.toString()
}

Variable parameter method call

println(append('h', 'e', 'l', 'l', 'o'))

2.3, method scope

In Kotlin, methods can be declared at the top level of the file, which means you don't need to create a class to store a method like in Java.

In addition to top-level methods, methods in Kotlin can also be declared in local scope, as member methods and extension methods.

2.3.1, local method

Local method writing

fun rand(): Int {
    
    
	// 局部方法
    fun square(v: Int): Int {
    
    
        return v * v
    }
	
	// 生成 0 到 100 的随机数(包括0、100)
    val v1 = (0..100).random()
    return square(v1)
}

Local method call

println(rand())

Three, Lambda expression

Java started to support Lambda expressions in Java 8. At present, Lambda syntax has been widely used in Java. Lambda expressions can be understood as a kind of syntactic sugar. Fortunately, Kotlin has already supported this as soon as open source. Kind of grammar.

Lambda as the basis of method programming, its syntax is also quite simple. Let me first understand the simplicity of Lambda expressions through a simple code demonstration.

Click event, Lambda expression is not used

view.setOnClickListener(new View.OnClickListener() {
    
    
    @Override
    public void onClick(View v) {
    
    
        Toast.makeText(context, "Lambda 简洁之道", Toast.LENGTH_LONG).show();
    }
});

Click event, use Lambda expression

view.setOnClickListener {
    
     v -> Toast.makeText(context, "Lambda简洁之道", Toast.LENGTH_LONG).show() }

3.1, Lambda expression syntax

No parameters

val/var 变量名 = {
    
     操作的代码 }
fun test() {
    
    
    println("无参数")
}

// 将上述代码改造成使用 Lambda 表达式代码
val test1 = {
    
     println("无参数") }

There are parameters

val/var 变量名 : (参数的类型,参数类型,...) -> 返回值类型 = {
    
    参数1,参数2... -> 操作参数的代码 }

// 此种写法:即表达式的返回值类型会根据操作的代码自推导出来。
val/var 变量名 = {
    
     参数1 : 类型,参数2 : 类型, ... -> 操作参数的代码 }
fun test2(a: Int, b: Int): Int {
    
    
    return a + b
}

// 将上述代码改造成使用 Lambda 表达式代码
val test3: (Int, Int) -> Int = {
    
     a, b -> a + b }
// Lambda 表达式代码简化
val test4 = {
    
     a: Int, b: Int -> a + b }

3.2. Know it in Kotlin

it is not a keyword in Kotlin. It is used when there is only one parameter of a Lambda expression in a higher-level method. It can be used to use this parameter. It can be expressed as the implicit name of a single parameter. It is the Kotlin language Agreed.

Implicit name of a single parameter

// 过滤掉数组中小于 5 的元素,这里的 it 就表示每一个元素
fun test5() {
    
    
    val arr = arrayOf(1, 2, 3, 4, 5)
    println("test5${arr.filter { it < 5 }}")
}

3.2. Use _ in Lambda expressions

When using a Lambda expression, you can use an underscore (_) to indicate an unused parameter, which means that this parameter will not be processed.

When traversing the Map collection, the usefulness is very obvious

fun test6() {
    
    
    val map = mapOf("key1" to "value1", "key2" to "value2", "key3" to "value3")
    
    map.forEach {
    
     (key, value) ->
        println("$key \t $value")
    }

    // 不需要key的时候
    map.forEach {
    
     (_, value) ->
        println(value)
    }
}

Fourth, the complete code

fun main() {
    
    
    println("functionLearn: ${functionLearn(101)}")
    Person().test1()
    Person.test2()
    println("umUtil.double(2): ${NumUtil.double(2)}")
    println("double(2): ${double(2)}")
    println(append('a', 'b', 'c'))
    println(magic())

    // lambda
    test1()
    println(test3(1, 3))
    test5()
    test6()
}

fun plus(a: Int, b: Int): Int {
    
    
    return a + b
}

fun functionLearn(days: Int): Boolean {
    
    
    return days > 100
}

class Person {
    
    
    /**
     * 成员方法
     */
    fun test1() {
    
    
        println("成员方法")
    }

    companion object {
    
    
        fun test2() {
    
    
            println("companion object 实现类方法")
        }
    }
}

/**
 * 整个静态类
 */
object NumUtil {
    
    
    fun double(num: Int): Int {
    
    
        return num * 2
    }
}

/**
 * 单表达式方法,当方法当个表达式时,可以省略花括号并且在 = 符号之后指定代码体即可
 */
fun double(x: Int): Int = x * 2


/**
 * 默认值,方法参数可以由默认值,当省略相应的参数时使用默认值。与Java相比,这可以减少重载数量
 */
fun read(b: Array<Byte>, off: Int = 0, len: Int = b.size) {
    
    

}

/**
 * 可变数量参数
 */
fun append(vararg str: Char): String {
    
    
    val result = StringBuffer()
    for (char in str) {
    
    
        result.append(char)
    }

    return result.toString()
}

/**
 * 局部方法
 */
fun magic(): Int {
    
    
    fun foo(v: Int): Int {
    
    
        return v * v
    }

    val v1 = (0..100).random()
    return foo(v1)
}


/**
 * 无参数情况
 */
fun test() {
    
    
    println("无参数")
}

val test1 = {
    
     println("无参数") }// lambda代码


/**
 * 有参数
 */
fun test2(a: Int, b: Int): Int {
    
    
    return a + b
}

val test3: (Int, Int) -> Int = {
    
     a, b -> a + b }// lambda代码
val test4 = {
    
     a: Int, b: Int -> a + b }// lambda代码简化

fun test5() {
    
    
    val arr = arrayOf(1, 2, 3, 4, 5)
    println("test5${arr.filter { it < 5 }}")
}

fun test6() {
    
    
    val map = mapOf("key1" to "value1", "key2" to "value2", "key3" to "value3")
    map.forEach {
    
     (key, value) ->
        println("$key \t $value")
    }

    // 不需要key的时候
    map.forEach {
    
     (_, value) ->
        println(value)
    }
}

Guess you like

Origin blog.csdn.net/weixin_38478780/article/details/108904251