Search code examples
javaintellij-ideakotlincompanion-object

Classifier JSONObject does not have a 'companion object, and thus must be initialized here


import org.json.JSONObject
JSONObject deviceInformation = ...

enter image description here

I tried to create a companion object like this, but not really working... sorry pretty noobie in Java and Kotlin.... enter image description here

and yes, JSONObject is imported correctly with

import org.json.JSONObject


Solution

  • You're using incorrect syntax. Variables in Kotlin are declared like:

    [var/val] name: OptionalExplicitType = something
    

    Which means JSONObject var instance:... isn't allowed.

    Change that to:

    var instance: JSONObject = ...
    

    It's also important that you set it. Since it looks like you're trying to create a singleton, you can just use an object instead of a class.

    If you feel like doing it the old fashioned way, make it nullable:

    var instance: JSONObject? = null
    

    Then check if it's null, initialize, set and return of it is, otherwise return the current value.

    If this isn't your goal though, you still need to initialize it, unless you make it lateinit. But if you do that, you need to initialize it before attempting to access it, or it will throw an exception.