Skip to content

Instantly share code, notes, and snippets.

@jkasten2
Last active April 26, 2017 06:39
Show Gist options
  • Save jkasten2/6f364e7a8ff51271d1e7263ab377b923 to your computer and use it in GitHub Desktop.
Save jkasten2/6f364e7a8ff51271d1e7263ab377b923 to your computer and use it in GitHub Desktop.
// Singleton pattern - static way to get instance
// Example 1 - Basic
class ExampleClassName {
// A "companion object" is required to make "static" methods / properites.
companion object {
// Property - private stetter, internal getter
// @JvmStatic - Only required if used outside of Kotlin
@JvmStatic lateinit var instance: Context private set
}
}
// Example 2 - inline - For possible efficiency. (Haven't tested Java output)
class ExampleClassName {
companion object {
// Backing variable
var mInstance: Context? = null
// Property with getter
@JvmStatic val instance: Context? inline get() = mInstance
}
}
// Example 3 - Create Object instead of class.
object ExampleClassName {
}
// Now ExampleClassName can be used link an instance.
// NOTE: Does not work for if inheriting from the Android Application class
// Runtime error is thrown due to different constructor.
// An inner class can access the parent instance like the following:
this@ParentClass
// Shorthand for if not null
someVar ?:
System.out.println("someVar is NOT null")
// This is the same as
if (someVar != null)
System.out.println("someVar is NOT null")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment