随播对象的文档具有以下示例
class MyClass {
companion object Factory {
fun create(): MyClass = MyClass()
}
}
Run Code Online (Sandbox Code Playgroud)
这Factory是伴随对象的名称.然后继续说:
可以省略伴随对象的名称,在这种情况下
Companion将使用名称:
但是,我没有看到使用伴随对象名称的示例.
因为每个类只能有一个伴侣对象(否则你会收到Only one companion object is allowed per class错误),这个名字对我来说就像是一些非常无用的语法糖.
同伴对象的名称实际上可以用于什么?为什么有人会为此使用任何名称呢?
Kotlin代码是这样的:
class Foo {
companion object {
fun a() : Int = 1
}
fun b() = a() + 1
}
Run Code Online (Sandbox Code Playgroud)
可以简单地改为
object FooStatic {
fun a() : Int = 1
}
class Foo {
fun b() = FooStatic.a()
}
Run Code Online (Sandbox Code Playgroud)
我知道伴侣对象可以用作真正的java静态函数,但使用伴侣对象还有其他优点吗?
自从Google使Kotlin成为Android的一流语言以来,与如何以Kotlin的“ Java风格”执行某些事情有关的问题就越来越多。最常见的是如何static在Kotlin中进行变量设置。那么,如何使Kotlin成为static变量和函数呢?
在Java中我有以下课程
public class Instruction {
public static Instruction label(String name) {
return new Instruction(Kind.label, name, null, 0);
}
public static Instruction literal(int value) {
return new Instruction(Kind.intLiteral, null, null, value);
}
public static Instruction literal(boolean value) {
return new Instruction(Kind.boolLiteral, null, null, value ? 1 : 0);
}
public static Instruction command(String name) {
return new Instruction(Kind.command, name, null, 0);
}
public static Instruction jump(String target) {
return new Instruction(Kind.jump, target, null, 0);
}
public static Instruction branch(String ifTarget, String …Run Code Online (Sandbox Code Playgroud) 在Java和Android中,我们可以这样做:
public static MyApplication extends Application {
private static Context appContext;
public void onCreate() {
appContext = this;
}
public static Context getAppContext() {
return appContext;
}
}
Run Code Online (Sandbox Code Playgroud)
所以,在其他地方,我们可以这样做:
appContext = MyApplication.getAppContext();
Run Code Online (Sandbox Code Playgroud)
我们如何在Kotlin做到这一点?过去一小时左右,我一直在围着圈子走.
提前致谢.
//编辑也许我应该更清楚.我的意思是我们如何在Kotlin中编写以上内容并在Kotlin中使用它.