当前位置:网站首页>Kotlin function
Kotlin function
2022-07-26 08:26:00 【Peace of mind】

Catalog
The return value of the function
The parameters of the function
Default parameters when declaring
When using keywords to pass parameters
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
边栏推荐
- QT uses QSS to make a beautiful login interface (hand-in-hand teaching)
- Software engineering -- dental clinic -- demand acquisition
- 2022/7/7 exam summary
- 正则表达式作业
- Burp suite Chapter 6 how to use burp spider
- Exam summary on June 27, 2022
- Basic music theory rhythm connection problem, very important
- Two ways to monitor the change of user points
- 2022-7-9 personal qualifying 6 competition experience
- OSPF总结
猜你喜欢

2022-7-7 personal qualifying 4 competition experience

C # get the information of the selected file

Burp Suite - Chapter 1 burp suite installation and environment configuration

外卖小哥,才是这个社会最大的托底

OSPF summary

Team members participate in 2022 China multimedia conference
![[GUI] GUI programming; AWT package (interface properties, layout management, event monitoring)](/img/25/475c91d7e673fda3930e5a69be0f28.png)
[GUI] GUI programming; AWT package (interface properties, layout management, event monitoring)

Burp suite Chapter 5 how to use burp target

Seq2seq and attention model learning notes

QT note 1
随机推荐
Understand microservices bit by bit
Apple's tough new rule: third-party payment also requires a percentage, and developers lose a lot!
The most complete network: detailed explanation of six constraints of MySQL
CentOS install mysql5.7
随机分布学习笔记
Awk operation
Super nice navigation page (static page)
[June 29, 2022] examination summary
Exam summary on July 13, 2022
Team members participate in 2022 China multimedia conference
宇宙第一 IDE 霸主,换人了。。。
2022/7/12 exam summary
2022/7/7 exam summary
vim跨行匹配搜索
这是一张图片
2022 7/5 exam summary
日常一记(11)--word公式输入任意矩阵
shell编程
How WPS sets page headers page by page
2022年全国职业院校技能大赛“网络安全”竞赛试题文件上传渗透测试答案Flag