Last active
April 26, 2017 06:39
-
-
Save jkasten2/6f364e7a8ff51271d1e7263ab377b923 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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