Function declarations use the fun keyword parameter in the form of name: type to indicate that the name on the left is the type of the parameter on the right, and the type of the return value after the last colon. If the function has no return value, it can be omitted or replaced by Unit.
fun double(x: Int): Int {
return 2 * x
}
Parameters can have default values such as the one above (x: Int = 0)
Usage:
val result = double(2)
When a function returns a single expression, curly braces can be omitted and the code body can be specified after the = symbol:
fun double(x: Int): Int = x * 2
Variable number of parameters (Varargs)
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
}
Allows a variable number of parameters to be passed to a function:
val list = asList(1, 2, 3)
Functional scope
Functions can be declared at the top of the file in Kotlin, which means that you don't need to create a class to save a function like some languages such as Java, C# or Scala. In addition to top-level functions, functions in Kotlin can also be declared in local scope, as member functions and extended functions.
Kotlin supports local functions, that is, a function within another function:
fun dfs(graph: Graph) {
fun dfs(current: Vertex, visited: Set<Vertex>) {
if (!visited.add(current)) return
for (v in current.neighbors)
dfs(v, visited)
}
dfs(graph.vertices[0], HashSet())
}
Local functions can access local variables of external functions (that is, closures), so visited can be a local variable in the previous example:
fun dfs(graph: Graph) {
val visited = HashSet<Vertex>()
fun dfs(current: Vertex) {
if (!visited.add(current)) return
for (v in current.neighbors)
dfs(v)
}
dfs(graph.vertices[0])
}
A generic function function can have generic parameters, which are specified by using angle brackets before the function name:
fun <T> singletonList(item: T): List<T> {
// ......
}
Higher order function
Higher-order functions are functions that use functions as parameters or return values
Lambda expression
- lambda expressions are always enclosed in braces
- Its parameters (if any) are declared before - > (parameter types can be omitted)
- The body of the function (if it exists) follows - >.
Another example of higher-order functions is the map() method in list
fun <T, R> List<T>.map(transform: (T) -> R): List<R> {
val result = arrayListOf<R>()
for (item in this)
result.add(transform(item))
return result
}
Example:
val ints = listOf<Int>(1,2,3,4,5,5)
//You can call it as follows
val resmap = ints.map {
value -> value * 2
}
Log.i("resmap",resmap.toString());
//Result
12-18 13:54:32.147 9639-9639/com.chs.kotlintext I/resmap: [2, 4, 6, 8, 10, 10]
Another useful convention is that if a function literal value has only one parameter, its declaration can be omitted (along with - >) and its name is it.
So the above example can be written as follows
val resmap = ints.map {
it * 2
}
//The return value is the same as above.
12-18 14:00:13.812 10038-10038/com.chs.kotlintext I/resmap: [2, 4, 6, 8, 10, 10]
Inline
Use inline keywords
Inline is currently mainly used in the code whose function parameters are lambda expressions, which can improve the efficiency of order functions.
inline fun <T> lock(lock: Lock, body: () -> T): T {
// ......
}
The inline modifier affects the function itself and the lambda expression passed to it: all of this is inlined to the caller. If there are more than two lambda parameters, just associate one, the noinline keyword is used.
inline fun foo(inlined: () -> Unit, noinline notInlined: () -> Unit) {
// ......
}
Association
In Kotlin 1.1+, the cooperative equation is experimental.
There's a lot to be said about the protocol.
https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md
Simple example
Add the following reference to the project build.gradle file
compile 'org.jetbrains.kotlinx:kotlinx-coroutines-core:0.20'
launch starts a new collaboration without blocking the current thread and returns the reference to the collaboration as a Job. When the job is cancelled, the collaboration is cancelled.
launch { // Start a new collaboration in the background and continue
delay(1000L) // Non-blocking delay of 1 second (default time unit is ms)
Log.i("launch","World") // Delayed printing
}
Log.i("launch","Hello") // The main thread continues when the co-process is delayed
Print results:
12-18 16:52:25.827 17383-17383/com.chs.kotlintext I/launch: Hello
12-18 16:52:26.831 17383-17428/com.chs.kotlintext I/launch: World