[Kotlin beginner] function (method)

Posted by alconebay on Tue, 07 Dec 2021 03:40:16 +0100

About the author: CSDN blog expert, Huawei cloud sharing expert certification

Series column: Kotlin beginner

Learning and communication: three people must have my teacher; Choose the good and follow it, and change the bad.

catalogue

function

Function header

Function parameters

Unit function

Nothing type

Function name in backquotes

Use spaces and special characters to name functions

Kotlin and Java interoperability

expand

Anonymous function

it keyword

Function types and implicit returns

Anonymous function parameters

Type inference

Nonparametric type inference

Type inference with parameters

Define a function: the parameter is a function

Abbreviation

Function reference

The return type of the function is anonymous

function

         The concepts of function and method are often confused. What is the relationship and difference between them? In fact, there is no difference between them, but they are called differently in different languages. They are commonly called methods in Java. In Kotlin, it is generally called function. The point is: function and method are the same thing. Don't make a mistake.

Function header

         practice

fun main() {
    println(doUserInfo("ShuaiCi", 18))
}

private fun doUserInfo(name:String,age:Int):String{
    return "$name Already this year $age Oh"
}

Function parameters

  • Default values for the parameters of the function
    • If you do not intend to pass in a value parameter, you can specify a default value for the parameter in advance

  • Named function parameters
    • If you use named value parameters, you can ignore the order of value parameters (which can be used when there are too many parameters)

         practice

fun main() {
    println(doUserInfo("ShuaiCi", 18))
    //If you use named value parameters, you can ignore the order of value parameters
    println(doUserInfo(age = 6, name = "Kotlin"))

    //The default parameter is not required
    println(doScUserInfo("Android"))
    //Transmissible age
    println(doScUserInfo("Java",30))
}

private fun doUserInfo(name: String, age: Int): String {
    return "$name Already this year $age Oh"
}

//Default parameter: specify a default value of 15 for age in advance
private fun doScUserInfo(name: String, age: Int = 15): String {
    return "$name Already this year $age Oh"
}

Unit function

         Return without parameters > return to Unit by default, which is optional

         It is similar to void in the Java language, except that Unit is a singleton class rather than a keyword

         practice

fun main() {
    println(doUnit("ShuaiCi", 18))
    println(doUnit2("ShuaiCi", 18))
}
//Return without parameters > return to Unit by default, which is optional
//It is similar to void in the Java language, except that Unit is a singleton class rather than a keyword
private fun doUnit(name: String, age: Int):Unit {
    println("$name Already this year $age Oh")
}
//Do not write: Unit   The same thing
private fun doUnit2(name: String, age: Int) {
    println("$name Already this year $age Oh")
}

Nothing type

         The task of TODO function is to throw an exception, that is, never expect it to run successfully and return Nothing. Terminate the code run without returning any type. You can use TODO() directly.

Note: it is not a comment prompt, which will terminate the program.

         practice

fun main() {
    println("-----start-----")
    TODO("Termination procedure")
    println("-----end-----")
}

         TODO function

@kotlin.internal.InlineOnly
public inline fun TODO(reason: String): Nothing = throw NotImplementedError("An operation is not implemented: $reason")

Function name in backquotes

  • Kotlin can name functions with spaces and special characters, but the function name should be enclosed in a pair of backquotes. (available during testing)

  • In order to support the interoperability between Kotlin and Java, Kotlin and Java each have different reserved keywords and cannot be used as function names. Any conflict can be avoided by enclosing the function names in backquotes.

Use spaces and special characters to name functions

         practice

fun main() {
    `20211202 World symmetry day`("Official account: handsome times")
}
private fun `20211202 World symmetry day`(name :String ){
    println(name)
}

         This tip is: identifiers are not allowed in Android projects. Operation is not affected.

Kotlin and Java interoperability

Java code

public class Test {
    public static final void fun(){
        System.out.println("come from Java Cordial greetings from");
    }
}

Kotlin

fun main() {
    //Use spaces and special characters to name functions
    `20211202 World symmetry day`("Official account: handsome times")
    //Kotlin and Java interoperability
    Test.`fun`()
}

Error reporting

expand

Anonymous function

         Functions that are defined without names are called anonymous functions. Anonymous functions are usually passed to or returned from other functions as a whole. With it, we can make special rules as needed and easily customize the built-in functions in the standard library.

    {} stands for anonymous functions.

it keyword

         When an anonymous function has only one parameter, you can use the it keyword to represent the parameter name. When you need to pass in two value parameters, the it keyword cannot be used. Here's a brief understanding, which will be used in later practice.

Function types and implicit returns

         The type of the function is determined by the type of the passed in parameter and the return value.

         Implicit return: except in rare cases, anonymous functions do not need the return keyword to return data. Anonymous functions will implicitly or automatically return the result of the last line of the function body.

         practice

fun main() {
    //1. Declare the input of the function ()   Output String
    val scFun :() -> String
    //2. Implementation function
    scFun = {
        val name = "Shuai Ci"
        //  Anonymous functions do not need to write retrun, and the last line is the return value
        "$name It's a war scum"
    }
    //Don't forget to add () here. This is a function, not an attribute
    println(scFun())
}

         Then you will find a dotted line under the first step. Let's operate it.

         The code is as follows, which is more concise

fun main() {
    //1. Declare the input of the function ()   Output String
    //2. Implementation function
    val scFun :() -> String = {
        val name = "Shuai Ci"
        //  Anonymous functions do not need to write retrun, and the last line is the return value
        "$name It's a war scum"
    }
    println(scFun())
}

Anonymous function parameters

         Anonymous functions can take no parameters or one or more parameters of any type.

         When parameters are required, the type of the parameter is placed in the type definition of the anonymous function, and the parameter name is placed in the function definition.

practice

fun main() {
    //With parameters
    val scFun2: (Int) -> String = { age ->
        val name = "Shuai Ci"
        //  Anonymous functions do not need to write retrun, and the last line is the return value
        "$name It's a war $age residue"
    }
    println(scFun2(16))
}

         Here is a parameter. Let's try to use the it keyword

         it keyword practice

         Look at 1. There is also a warning: it here represents the incoming Int.

         When the incoming parameters here become multiple, it cannot be used.

Type inference

         When defining a variable, if you have assigned an anonymous function to it as a variable, you do not need to display the specified variable type.

Nonparametric type inference

         practice

    //Nonparametric type inference
    val scFun4 = {
        val name = "Shuai Ci"
        //  Anonymous functions do not need to write retrun, and the last line is the return value
        "$name Nonparametric type inference"
    }
    println(scFun4())

Type inference with parameters

         practice

    //Type inference with parameters
    val scFun5 = { age:Int,money:Float->
        val name = "Shuai Ci"
        //  Anonymous functions do not need to write retrun, and the last line is the return value
        "$name Type inference with parameters $age Years old, in my pocket $money"
    }
    println(scFun5(15,1.25f))

Define a function: the parameter is a function

         One function as an argument to another function.

         practice

fun main() {
    //2. Declarative function
    val bookBeginner = {bookName:String,price:Double->
        "$bookName The pricing is: $price"

    }
    //3. Call the function and pass in the function bookbeginer
    learningAndroidBook("Shuai Ci",bookBeginner)
}
//1. Define a function (learningandroid book): the parameter is the function (bookPrice)
fun learningAndroidBook(name:String,bookPrice:(String,price:Double)->String){
    println("$name come from learningAndroidBook ")
    println(bookPrice(name,48.88))
}

Abbreviation

         If the lambda parameter of a function comes last or is the only parameter, the pair of parentheses surrounding the lambda value parameter can be omitted.

fun main() {
    //4. Abbreviation (parameters last)
    learningAndroidBook("Kotlin Abbreviation"){bookName:String,price:Double->
        "$bookName The pricing is: $price"
    }
    //5. Abbreviation (only one parameter), () omitted
    learningAndroidBook2{bookName:String,price:Double->
        "$bookName The pricing is: $price"
    }
}
//Define a function whose parameters are functions
fun learningAndroidBook2(bookPrice:(String,price:Double)->String){
    println(bookPrice("Kotlin Abbreviation-The only parameter",48.88))
}

Function reference

         To pass functions as parameters to other functions, in addition to passing lambda expressions (anonymous functions), kotlin also provides other methods to pass function references. Function references can convert a named function into a value parameter. Function references can be used wherever lambda expressions are used.

         practice

fun main() {
    //6.2 function reference
    learningAndroidBook("Function reference",::bookPriceName);
}
//six point one   Define named functions
fun bookPriceName(bookName:String,price:Double):String{
    //return should be added to the named function
    return "$bookName The pricing is: $price"
}
//1. Define a function (learningandroid book): the parameter is the function (bookPrice)
fun learningAndroidBook(name:String,bookPrice:(String,price:Double)->String){
    println("$name come from learningAndroidBook ")
    println(bookPrice(name,48.88))
}

The return type of the function is anonymous

fun main() {
    //use
    val funName = helloSc()
    println(funName(15))
}
//A named function is defined, and the return type is anonymous
fun helloSc():(Int)->String{
    val name = "Slag times"
    //Anonymous function returned, parameter passed in
    return {age->
        //Anonymous function return type
        "$age Year old $name"
    }
}

Topics: Java Android kotlin