简体   繁体   English

kotlin 中的伴生对象和 java 中的替换有什么用

[英]What is the use of companion object in kotlin and replacement in java

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.您的行意味着有一个名为funAfterPermission的 var,它接受一个函数(高阶函数)作为参数,该参数在 java 中返回等效于 void 它接受一个没有参数的方法。 The var itself is null by default and can be null.默认情况下,var 本身为 null,并且可以为 null。

var funAfterPermission: (() -> Unit)? = null

Example:例子:

fun test(): (() -> Unit)? {
        println("test")
        return null
}

funAfterPermission = test()

Its like an eval in several languages.它就像多种语言的eval It calls something in another function but doesnt assign anything since it returns Unit.它在另一个函数中调用一些东西,但不分配任何东西,因为它返回 Unit。

companion objects are used to get the "static" behaviour from java. 伴随对象用于从 java 获取“静态”行为。 You can access your funAfterPermission using YourClass.funAfterPermission = ....您可以使用YourClass.funAfterPermission = ....访问您的 funAfterPermission。

companion object is the replacement for singleton in Java. companion object是 Java 中单例的替代品。

() -> Unit represent a delegate. () -> Unit代表一个委托。 It can be divide into () and Unit .它可以分为()Unit () means the delegate should accept nothing as parameter. ()表示委托不应接受任何参数。 Unit means the delegate return nothing (same as void in Java). Unit表示委托不返回任何内容(与 Java 中的 void 相同)。 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 .例如, (Int, String) -> String表示它要求第一个参数为Int ,第二个参数为String ,并返回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.委托由::语法分配,可以像普通函数一样调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM