当前位置:网站首页>Kotlin function

Kotlin function

2022-07-26 08:26:00 Peace of mind

Kotlin Functional mind map
Kotlin Functional mind map

Catalog

Declaration of functions

Visibility modifier   link

public

internal

protected

private

summary

The return value of the function

The parameters of the function

Default parameters when declaring

When using keywords to pass parameters

Variable parameters

Special functions use

Member functions

Single expression functions


Declaration of functions

   Kotlin The keyword used for function declaration in is :fun

    The specific format of the declaration is : Visibility modifier fun Function name ( Parameter name : Parameter type ) : return type  { The body of the function }

    When using : No return value can Function name ( Parameters use )

                  Those with return values can var Variable name = Function name ( Parameters use )

    Examples are as follows :

// Declared at the top Int Array summation function 
public fun getSum(args:Array<Int>):Int{
    var sum=0
    for (i in args){
        sum+=i
    }
    return sum
} //public Omission , Different files can be accessed 

private fun sub_arr(args1: Array<Int>, args2: Array<Int>): Array<Int> {
// private Decorated top-level function , It can only be accessed in this document 
//  This function realizes the subtraction of the corresponding elements of the array , Generally, two arrays are required , If unequal length , Then long - short 
    var res: Array<Int>
    if (args1.size>args2.size){
        res=args1
        for (i in args2.indices){
            res[i]=args1[i]-args2[i]
        }
    }else{
        res=args2
        for (i in args1.indices){
            res[i]=args2[i]-args1[i]
        }
    }
    return res
}

internal fun no_return(args:Int=5){
// No return value and default parameters 
    println(args)
}

fun main(args:Array<String>){
//  Declared at the top main function , The visibility modifier defaults to public, The return value is Unit type 
//  Parameter is String Array , The parameter name is args
    var arr1= arrayOf(1,3,5,7,9)
    var arr2= arrayOf(2,4,6,8)
    val sum=getSum(arr1)
    println(sum)// 25
    for (i in sub_arr(arr2,arr1)){
        print("$i ")// -1 -1 -1 -1 9
    }
    println()
    no_return() //5 
    no_return(8) //8
}

Visibility modifier   link

public

    public The modifier is Kotlin The default modifier in , Omit not to write , On the top floor 、 class 、 Can be used locally , Maximum visibility , Generally, all sub regions under the parent region are visible

internal

     internal yes Kotlin Peculiar , It is visible in the module , It can be on the top floor , Class

     Kotlin The module of refers to a set of compiled Kotlin Source file : It could be a IntelliJ IDEA modular ; One Maven project ; One Gradle Source set ; A set of calls Ant Task compiled file

protected

   protected Modifiers are similar to those encountered in previous languages , Can only be used in a class , It is generally accessible in this class and inherited classes

private

     private The modifier is also consistent with the previous language , It can be on the top floor 、 Use in class , Generally, it can be accessed in this class or in this document

summary

Only division can be used at the top layer protected External 3 A modifier

Within class 4 Modifiers can be used

Local declarations within blocks can only be used public Modifying variables

// learn.kt
package kotlin_learn

private fun f() {  } //  stay  learn.kt  See inside 

public var a: Int = 5 //  Variable a It can also be seen in other documents ( You can make it accessible by importing packages )
private var b:Int = 0   //  Variable b Only in learn.kt  See inside 
    
internal val c= 6    //  Variable c Visible within the same module 

open class A{
    private val a = 1 // Visible in the current class 
    protected open val b = 2 // Visible within the current class and its inherited classes 
    internal val c = 3 // Visible in the current class and the same module class 
    val d = 4  //  Default  public , With class A The visibility of 
    
    protected class Nested { // Inner class and protected
        public val e: Int = 5 // attribute e Access rights follow Nested Class visibility 
    }
}

class Subclass : A() { // Inherit A
    // a  invisible 
    // b、c、d  so 
    // Nested  and  e  so 

    override val b = 5  //  Rewrote b
}

class B(o:A) {  // Not an inherited relationship , primary constructor ,B Only access A Of public and interna attribute 、 Method 
    // o.a、o.b  invisible 
    // o.c  and  o.d  so ( Same module )
    // A.Nested  invisible ,Nested::e  Nor visible 
}

The return value of the function

  Kotlin The return value types of functions in can be roughly divided into two types Unit And have return value types

  Generally, if a function has no return value , Then the function declaration may not write the return value and return sentence (return If the sentence is written , Can be directly to write return)

  When a function has a specific return value , You need to specify the type of the return value in the declaration , It's written in ": return type "

And when the return value is nullable , Nullable type must also be written in the return value type

fun printArr(array: Array<Int?>){
    for (i in array){
        print("$i ")
    }
    println()
    return //return Omission 
}
fun getSum(array: Array<Int?>):Int?{
    var a=0
    var sign=true
    for (i in array){
        if (i!=null){
            a+=i
            sign=false
        }
    }
    return if (sign) null else a // Ternary expression 
}
fun main(args:Array<String>){
    var arr:Array<Int?> = arrayOf(1,3,5,7,9)
    printArr(arr) // 1 3 5 7 9
    println(getSum(arr))// 25
    arr= arrayOf(null)
    printArr(arr)// null
    println(getSum(arr)) // null
}

The parameters of the function

    When a function is declared , The declaration of general parameters is based on Parameter variable name : Parameter type The format of

Default parameters when declaring

    The meaning of default parameters will not be repeated , Here we mainly talk about the use of default parameters

    Generally, it still needs to follow Set... From right to left Logic of transferring parameters in a convenient location

    Use format : Parameter variable name : Parameter type = value

internal fun no_return(args:Int=5){
// No return value and default parameters 
    println(args)
}

When using keywords to pass parameters

    Pass the key words to , When the function is called , Functional () Inside , Must take Parameter variable name = Value or variable The formal transfer parameters

    Use this parameter transfer method , It is not necessary to follow the default parameter setting sequence from right to left

fun add_arr(addition:Int=1,array: Array<Int?>):Array<Int?>{

    for (i in array.indices){
        array[i] = array[i]?.plus(addition)
    }
    return array
}
fun printArr(array: Array<Int?>){
    for (i in array){
        print("$i ")
    }
    println()
    return //return Omission 
}
fun main(args:Array<String>){
    var arr:Array<Int?> = arrayOf(1,3,5,7,9)
    add_arr(array = arr)
    printArr(arr)
    add_arr(-2,arr)
    printArr(arr)
}

Variable parameters

  When the length of a parameter variable that needs to be used in a function is not fixed , You can use variable modifiers vararg modification , By vararg The decorated parameter variable is equivalent to an array , The length of the array is determined by the parameters

  Declaration format : Visibility modifier fun Function name ( Parameter name : type , vararg Parameter name : type )

  Generally speaking , Put variable parameters at the end of function parameter declaration , In order to better conform to the logic of position parameter transmission , But when using keywords to pass parameters , The declaration position of variable parameters can be arbitrary

fun myPrint(vararg args:Int){
    for (i in args){
        print("$i ")
    }
    println()
}

fun main(args:Array<String>){
    myPrint(1,2,3,4,5)
    myPrint(args = IntArray(3) { index -> (index * 3) }) 
    //lambda  Use of functions , This array is declared in the previous Kotlin Data types are described in the blog 
}

Special functions use

Member functions

    Functions declared in a class are called member functions

    Use of member functions : Class object . Function name ( Parameters ) 

Single expression functions

    When a function has a return value , And the function body can only be expressed as return Some expression In the form of , At this point, the { } Omission , use = Direct connection return The expression after , This representation is called a single expression function

fun myMultiply(a:Double ,b:Double)=a*b
原网站

版权声明
本文为[Peace of mind]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/201/202207181753182535.html