0

I'm trying to define a global variable in my application It is saying that the property must be defined or abstract. I've looked and tried to copy some soltuions but can't seem to get it to work

any advice appreciated.

package com.example.app.thisweekintown

import android.app.Application

class GlobalVars:Application() {

    var isConnected:Boolean

    }
BostonMacOSX
  • 1,369
  • 2
  • 17
  • 38

3 Answers3

3

You can define a global variable in Kotlin without initializing by using a keyword called lateinit

Ex:

lateinit var obj: ClassName
lateinit var str: String

If you try to accesse the global variable before initialization then you will get the following exception.

Caused by: kotlin.UninitializedPropertyAccessException: lateinit property obj/str has not been initialized.

To avoid the exception refer this

But lateinit is not support primitive types

lateinit var isConnected:Boolean//'lateinit' modifier is not allowed on properties of primitive types

Ref : https://stackoverflow.com/a/38769161/5898862

JEGADEESAN S
  • 566
  • 1
  • 6
  • 19
1

You need to either initialize the variable:

class GlobalVars : Application() {
    var isConnected: Boolean = false
}

or use lateinit as described in answer by JEGADEESAN.

Also, in case you are planning to always have single instance of GlobalVars, I believe you might be interested in object declarations: http://kotlinlang.org/docs/reference/object-declarations.html

object GlobalVars : Application() {
    var isConnected: Boolean = false
}
code_x386
  • 778
  • 3
  • 5
1

In the end I was calling the class incorrectly. I was instantiating an instance of the class and not just calling the variable as part of the application level. I'm going to rewrite things to use ViewModels but at this time I'm going to work with this as I need to move forward.

From an Activity I could get and set things with:

(applicationContext as GlobalVars).setSomeVariable(true)
(applicationContext as GlobalVars).getSomeVariable()

From a Fragment (activity.applicationContext as GlobalVars).setSomeVariable(true) (activity.applicationContext as GlobalVars).getSomeVariable()

I also rewrote the GlovalVars class to show the getters and setters:

class GlobalVars:Application() {

private var isConnected: Boolean = false

fun getSomeVariable(): Boolean {
    return isConnected
}

fun setSomeVariable(someVariable: Boolean) {
    this.isConnected = someVariable
}
BostonMacOSX
  • 1,369
  • 2
  • 17
  • 38