简体   繁体   English

使用伴侣对象返回Kotlin中的类的实例

[英]Using companion object to return an instance of the class in Kotlin

Android Studio 3.0 RC2
Kolin 1.1.51

I creating an Android App, and I want to return the instance of the class that extends Application and access the equivalent you would do using a static in Java. 我创建了一个Android应用程序,我想返回扩展Application的类的实例,并访问使用Java中的静态方法所做的等效操作。

class BusbyMoviesMainApplication : Application() {
    companion object {
        private val instance: BusbyMoviesMainApplication = BusbyMoviesMainApplication()

        @JvmStatic
        fun getBusbyInstance(): BusbyMoviesMainApplication {
            return instance
        }
    }
}

I am accessing it like this. 我正在这样访问它。 However, getCacheDir returns null 但是,getCacheDir返回null

BusbyMoviesMainApplication.getBusbyInstance().getCacheDir()

I can't see what I am doing wrong. 我看不到我在做什么错。

In Java I have done like this before, which works, I am trying to do the same in Kotlin: 在Java中,我以前这样做是可行的,但我想在Kotlin中做同样的事情:

public class BusbyMoviesApplication extends Application {
    private static BusbyMoviesApplication mBusbyMoviesApplication;

    public static BusbyMoviesApplication getInstance() {
        return mBusbyMoviesApplication;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mBusbyMoviesApplication = BusbyMoviesApplication.this;
    }
}

In the Kotlin code, you're calling the constructor of the Application subclass directly instead of letting the framework create it for you. 在Kotlin代码中,您直接调用Application子类的构造函数,而不是让框架为您创建它。 You could instead do what you did in the Java code, and initialize the instance property in the Application 's onCreate method (plus I shortened the getter a bit): 您可以改为执行Java代码中的操作,然后在ApplicationonCreate方法中初始化instance属性(此外,我稍微缩短了getter):

class BusbyMoviesMainApplication : Application() {
    companion object {
        private lateinit var instance: BusbyMoviesMainApplication

        @JvmStatic
        fun getBusbyInstance() = instance
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
    }
}

Based on the discussion in the comments below, this would perhaps be a more idiomatic solution for the getter: 根据以下评论中的讨论,对于getter来说,这可能是更惯用的解决方案:

class BusbyMoviesMainApplication : Application() {
    companion object {
        @JvmStatic
        lateinit var instance: BusbyMoviesMainApplication
            private set
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
    }
}

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

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