2019.07.03: You may not shine, but always warm light
Write a function
Functions in Kotlin are declared using the fun keyword:
class HelloPeiqiTest{
init {
var tempPrint= handleAge(12)
}
fun handleAge(age: Int){
println(age)
}
}Copy the code
General usage of functions
Call the function using the traditional method
var tempPrint= handleAge(12)Copy the code
Call member functions using dot notation
HelloPeiqiTest().handleage (12)// Create an instance of class HelloPeiqiTest and call handleAgeCopy the code
parameter
Function parameters are defined using Pascal notation, that is, name: type. Parameters are separated by commas. Each argument must have an explicit type:
fun handleAge(age: Int,str:String){
println(age)
}Copy the code
The default parameters
Function arguments can have default values, which are used when corresponding arguments are omitted. This reduces the number of overloads compared to other languages
Default values are defined by the = following the type and the given value.
class HelloPeiqiTest{
init {
var tempPrint= handleAge(12)
}
fun handleAge(age: Int,str: String="my age is:"){
println(str+age)
}
}Copy the code
The results of
------------start----------
my age is:12
------------stop----------Copy the code
Override methods always use the same default parameter values as base type methods. When overwriting a method with default parameter values, the default parameter values must be omitted from the signature:
Open class A {open fun foo(I: Int = 10) {... } } class B :AOverride fun foo(I: Int) {... } // Cannot have default values}Copy the code
If a default argument precedes an argument with no default value, the default value can only be used by calling the function with named arguments
Class peiqitest {init {tempPrint= handleAge(14)} class peiqitest {init {tempPrint= handleAge(num=14)} Int=12,num: Int){ println(num+age) } }Copy the code
If the last argument after the default argument is a lambda expression, it can be passed either inside or outside parentheses as a named argument:
Fun foo(bar: Int = 0, baz: Int = 1, qux: () -> Unit) {... } foo(1) { println("hello"} // Use the default value baz = 1 foo(qux = {println("hello"}) // Use two defaults bar = 0 and baz = 1 foo {println("hello"} // Use two defaults bar = 0 and baz = 1Copy the code
Named parameters
You can use named function arguments when calling a function. This comes in handy when a function has a large number of arguments or default arguments.
Class HelloPeiqiTest{init {// Call it with default arguments reformat("nihao") // When called with non-default arguments, the call looks like reformat("buhao".true.true.false.'_'// If we don't need all the arguments // if we need to change the default argument, use its named argument to assign values // so that we don't have to write all of the above."yibanban",wordSeparator = 'c')
}
fun reformat(str: String,
normalizeCase: Boolean = true,
upperCaseFirstLetter: Boolean = true,
divideByCamelHumps: Boolean = false,
wordSeparator: Char = ' ') {
println(str)
}
}Copy the code
When a function call mixes positional and named arguments, all positional arguments precede the first named argument. For example, it is allowed to call f(1, y = 2) but not f(x = 1, 2).
Variable number arguments (VARargs) can be passed in named form by using the asterisk operator
class HelloPeiqi{
init {
basicTest(strs = *arrayOf("1"."2"."3"))
}
fun basicTest(vararg strs:String){
strs.forEach {
println(it)
}
}
}Copy the code
Note that you cannot use the named parameter syntax when calling Java functions, because Java bytecode does not always reserve the names of function arguments.
Returns a function of Unit
If a function does not return any useful value, its return type is Unit. Unit is a type that has only one value, Unit. This value does not need to be explicitly returned, just as void does in Java.
fun printHello(name: String): Unit {
if(name ! = null) println("Hello ${name}")
else
println("Hi there!") / / `returnThe Unit ` or `return'is optional} Unit return type declaration is also optional. The code above is equal to funprintHello(name: String) {
if(name ! = null) println("Hello ${name}")
else
println("Hi there!") / / `returnThe Unit ` or `return'is optional}Copy the code
One expression function
When a function returns a single expression, you can omit the curly braces and specify the code body after the = symbol:
BasicTest2 println(basicTest2(2)) println(basicTest2(2))} fun basicTest(num: Int): Int = num * 5 fun basicTest2(num: Int): Int {return num * 5
}
}Copy the code
An explicit declaration of the return type is optional when the return value type can be inferred by the compiler
Functions with block bodies must always specify an explicit return type, unless they are intended to return Unit. The return type of functions with block bodies cannot be inferred, so the return type must be explicitly declared
BasicTest2 println(basicTest2(2)) println(basicTest2(2))} fun basicTest(num: Int)= num * 5 fun basicTest2(num: Int): Int {return num * 5
}
}Copy the code
Variable number of parameters (Varargs)
The argument to a function (usually the last one) can be marked with the vararg modifier:
class HelloPeiqi{
fun basicTest(vararg strs:String){
strs.forEach {
println(it)
}
}
}Copy the code
Allows a variable number of arguments to be passed to a function:
class HelloPeiqi {
init {
val list1 = asList(1, 2, 3)
val list2 = asList("ddd"."fff")
}
fun <T> asList(vararg ts: T): List<T> {
val result = ArrayList<T>()
for (t in ts) // ts is an Array
result.add(t)
return result
}
}Copy the code
Only one parameter can be labeled vararg. If the vararg argument is not the last one in the list, you can use the named parameter syntax to pass the value of the following argument, or, if the argument has a function type, by passing a lambda outside the parentheses.
When we call vararg-, we can pass arguments one by one, such as asList(1, 2, 3), or, if we already have an array and want to pass its contents to the function, we use the spread operator (preceded by *) :
Class HelloPeiqi {init {var list1 = arrayOf(1, 2, 3) val list2 = asList(4,*list1,6)} fun <T> asList(vararg ts: T): List<T> { val result = ArrayList<T>()for (t in ts) // ts is an Array
result.add(t)
return result
}
}Copy the code
Infix notation
Functions marked with the infix keyword can also be called using infix notation (ignoring the dot and parentheses of the call). Infix functions must meet the following requirements:
- They must be member functions or extension functions;
- They must have only one parameter;
- Its arguments cannot accept a variable number of arguments and cannot have default values.
Class HelloPeiqi {init {var num= 1 hah 5 println(num) // Call this function with infix notation var STR ="nihao"AppendNum 5 = var str2="nihao".appendNum(4)
println(str)
println(str2)
}
infix fun Int.hah(num:Int):Int{
return num*2
}
infix fun String.appendNum(num: Int):Int{
return num*4
}
}Copy the code
Note that infix functions always require the receiver and argument to be specified. When calling a method on the current recipient using infix notation, use this explicitly; It cannot be omitted like a regular method call. This is necessary to ensure non-fuzzy resolution.
class HelloPeiqi {
init {
add(1)
}
infix fun add(num:Int):Int{
return num*2
}
fun build(){// correct this.add(1) // correct add(12) // error add 12}}Copy the code
Function scope
In Kotlin functions can be declared at the top of the file, which means you don’t need to create a class to hold a function like some languages like Java, C#, or Scala do. In addition to top-level functions, functions in Kotlin can also be declared in local scopes, as member functions, and as extension functions.
Local function
Kotlin supports local functions, where one function is inside another function:
Local functions can access local variables of external functions (that is, closures)
fun add(num: Int) {
fun handleNum(tempNum: Int): Int {
return tempNum * 2
}
var x = 13
handleNum(x)
}Copy the code
A member function
Member functions are functions defined inside a class or object: member functions are called HelloPeiqi().add(12) in dot notation
Fun add(num: Int) {println(num)}} class peiqi {init {add(2)}Copy the code
Generic function
Functions can have generic arguments, specified by using Angle brackets before the function name
Fun <T> List(item: T): List<T> {...... }Copy the code
Summary: This part belongs to the combination of basic type to write some simple functions, the function call, the next part of the learning function advanced part.