“This is the sixth day of my participation in the First Challenge 2022. For details: First Challenge 2022”

A, functions,

Function and method are often confused. What are the differences between them? Actually, there’s no difference between them except that they’re called differently in different languages, and in Java they’re called methods. And in Kotlin it’s generally called a function. The point is: a function and a method are the same thing. Make no mistake.

1.1 the function head

practice

fun main(a) {
    println(doUserInfo("ShuaiCi".18))}private fun doUserInfo(name:String,age:Int):String{
    return "$nameAlready this year$ageOh"
}
Copy the code

1.2 Function Parameters

  • Default values for function arguments
    • If you do not intend to pass in value parameters, you can specify default values for the parameters beforehand
  • Named function parameter
    • If you use named value parameters, you can ignore the order of value parameters (this can be used when there are too many parameters).

practice

fun main(a) {
    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 age
    println(doScUserInfo("Android"))
    / / to the age
    println(doScUserInfo("Java".30))}private fun doUserInfo(name: String, age: Int): String {
    return "$nameAlready this year$ageOh"
}

// Default parameter: prespecify a default value of 15 for age
private fun doScUserInfo(name: String, age: Int = 15): String {
    return "$nameAlready this year$ageOh"
}
Copy the code

1.3 the Unit function

If no parameter is specified, Unit is returned by default

Similar to the Java language’s void, except that Unit is a singleton class rather than a keyword

practice

fun main(a) {
    println(doUnit("ShuaiCi".18))
    println(doUnit2("ShuaiCi".18))}// No parameter is returned. > Unit is returned by default
// Similar to the Java language void, except Unit is a singleton class instead of a keyword
private fun doUnit(name: String, age: Int):Unit {
    println($name = $age)}// Do not write :Unit also same same
private fun doUnit2(name: String, age: Int) {
    println($name = $age)}Copy the code

1.4 Nothing type

The job of a TODO function is to throw an exception, never expect it to succeed, and return Nothing. Terminates the code without returning any type. You can use TODO() directly.

Note: This is not a comment prompt and will terminate the program.

practice

fun main(a) {
    println("-----start-----")
    TODO("Termination procedure")
    println("-----end-----")}Copy the code

TODO function

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

1.5 Function name in inverted quotation marks

  • Kotlin can name functions using Spaces and special characters, but the function names are enclosed in a pair of back quotes. (Available for testing)

  • In order to support Kotlin and Java interoperability, while Kotlin and Java have different reserved keywords that cannot be used as function names, enclosing function names in backquotes avoids any conflicts.

1.6 Use Spaces and special characters to name functions

practice

fun main(a) {`20211202World Symmetry Day ("Public account: Shuaici")}private fun `20211202World Symmetry Day '(name :String){println(name)}Copy the code

The tip is: Identifiers are not allowed in Android projects. Operation is not affected.

1.7 Kotlin interoperates with Java

Java code

public class Test {
    public static final void fun(a){
        System.out.println("Greetings from Java"); }}Copy the code

Kotlin

fun main(a) {
    // Use Spaces and special characters to name functions
    `20211202World Symmetry Day ("Public account: Shuaici")
    //Kotlin interoperates with Java
    Test.`fun`(a)
}
Copy the code

An error condition

Second, the development

2.1 Anonymous Functions

Functions 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 easily customize the built-in functions in the standard library by making special rules as needed.

{} represents anonymous functions.

2.2 IT Keyword

For anonymous functions with only one argument, the IT keyword can be used to represent the parameter name. The IT keyword cannot be used when you need to pass in two value arguments. Here is a simple understanding of the use in the later practice.

2.3 Function types and implicit returns

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

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

practice

fun main(a) {
    //1, declare the function input () output String
    val scFun :() -> String
    //2
    scFun = {
        val name = "Handsome"
        // Anonymous functions do not need to write retrun, the last line is the return value
        "$nameHe's just a piece of crap."
    }
    // Don't forget to add (). This is a function, not an attribute
    println(scFun())
}
Copy the code

And then you’ll notice that there’s a dotted line underneath the first step, so let’s do that.

Here’s the code, which is even more concise

fun main(a) {
    //1, declare the function input () output String
    //2
    val scFun :() -> String = {
        val name = "Handsome"
        // Anonymous functions do not need to write retrun, the last line is the return value
        "$nameHe's just a piece of crap."
    }
    println(scFun())
}
Copy the code

2.4 Anonymous function parameters

Anonymous functions can take no arguments or one or more arguments 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(a) {
    / / parameters
    val scFun2: (Int) -> String = { age ->
        val name = "Handsome"
        // Anonymous functions do not need to write retrun, the last line is the return value
        "$nameIs a war$ageSlag"
    }
    println(scFun2(16))}Copy the code

So here’s a parameter and let’s try using the IT keyword

It keyword practice

Look at 1, and a warning: the it here stands for the Int passed in.

When the incoming parameters here become multiple, IT becomes unusable.

2.5 Type Inference

When you define a variable, you do not need to display the specified variable type if an anonymous function has been assigned to it.

2.5.1 no arguments

practice

    // No parameter type inference
    val scFun4 = {
        val name = "Handsome"
        // Anonymous functions do not need to write retrun, the last line is the return value
        "$nameNo parameter type inference"
    }
    println(scFun4())
Copy the code

2.5.2 Type Inference with Parameters

practice

    // Parameter type inference
    val scFun5 = { age:Int,money:Float->
        val name = "Handsome"
        // Anonymous functions do not need to write retrun, the last line is the return value
        "$nameParameter type inference$ageI'm old, pocket$money"
    }
    println(scFun5(15.1.25 f))
Copy the code

2.6 Defining a function: Arguments are functions

A function as an argument to another function.

practice

fun main(a) {
    //2
    val bookBeginner = {bookName:String,price:Double->
        "$bookNamePricing for:$price"

    }
    //3, call the function bookBeginner
    learningAndroidBook("Handsome",bookBeginner)
}
//1, define a function (learningAndroidBook) : the argument is function (bookPrice).
fun learningAndroidBook(name:String,bookPrice:(String.price:Double) - >String){
    println("$nameFrom learningAndroidBook")
    println(bookPrice(name,48.88))}Copy the code

2.6.1 Shorthand

If a function’s lambda arguments are last, or only, then the pair of parentheses enclosing the lambda value arguments can be omitted.

fun main(a) {
    //4.
    learningAndroidBook("Kotlin shorthand."){bookName:String,price:Double->
        "$bookNamePricing for:$price"
    }
    //5, shorthand (the only argument), () omitted
    learningAndroidBook2{bookName:String,price:Double->
        "$bookNamePricing for:$price"}}// Define a function
fun learningAndroidBook2(bookPrice:(String.price:Double) - >String){
    println(bookPrice("Kotlin shorthand - one parameter.".48.88))}Copy the code

2.7 Function Reference

To pass functions as arguments to other functions, Kotlin provides other methods besides passing lambda expressions (anonymous functions), passing function references, which convert a named function to a value parameter. Function references can be used wherever lambda expressions are used.

practice

fun main(a) {
    //6.2, function reference
    learningAndroidBook("Function reference",::bookPriceName);
}
//6.1 Defining named functions
fun bookPriceName(bookName:String,price:Double):String{
    // Add return to the named function
    return "$bookNamePricing for:$price"
}
//1, define a function (learningAndroidBook) : the argument is function (bookPrice).
fun learningAndroidBook(name:String,bookPrice:(String.price:Double) - >String){
    println("$nameFrom learningAndroidBook")
    println(bookPrice(name,48.88))}Copy the code

2.8 Function return type Is anonymous function

fun main(a) {
    / / use
    val funName = helloSc()
    println(funName(15))}// Define a named function with an anonymous return type
fun helloSc(a): (Int)->String{
    val name = "Dregs"
    // Return an anonymous function, age passed as an argument
    return {age->
        // Return type of an anonymous function
        "$ageAt the age of$name"}}Copy the code