companion object {
var funAfterPermission: (() -> Unit)? = null
}
What is the use of companion object in the above snippet and what is the meaning of line
var funAfterPermission: (() -> Unit)? = null
Your line means that there's a var with the name funAfterPermission
which accepts a function ( high order functions ) as parameter which returns the equivalent to void in java It acceps a method with no parameters. The var itself is null by default and can be null.
var funAfterPermission: (() -> Unit)? = null
Example:
fun test(): (() -> Unit)? {
println("test")
return null
}
funAfterPermission = test()
Its like an eval in several languages. It calls something in another function but doesnt assign anything since it returns Unit.
companion objects are used to get the "static" behaviour from java. You can access your funAfterPermission using YourClass.funAfterPermission = ....
companion object
is the replacement for singleton in Java.
() -> Unit
represent a delegate. It can be divide into ()
and Unit
. ()
means the delegate should accept nothing as parameter. Unit
means the delegate return nothing (same as void in Java). Combining them means it is a delegate that does not require any parameters and does not return anything.
(() -> Unit)?
means the delegate can be null.
For example, (Int, String) -> String
means it requires the first parameter to be Int
, the second parameter to be String
and it returns String
.
class Foo {
var greeting: () -> Unit = this::helloWorld
fun helloWorld() {
}
fun hello() {
greeting()
}
}
Delegate is assigned by ::
syntax and can be called like a normal function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.