I've just started using and started messing with abstract classes, override val's and singeltons. But, I've just encountered a really odd behaviour. My goal was to have an abstract class, and then create several singeltons that extends that abstract class. Since i want to require certain variables i created abstract val that then could be overridden in the subclasses (Instead of passing them through the constructor).
So i got 4 classes:
MainActivity:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val instance = Instance()
Log.d("MainActivity", "instance randObject: ${instance.randObject}")
Log.d("MainActivity", "instance randObject: ${instance.randObject.myProp}")
Log.d("MainActivity", "instance randObject: ${instance.randObject.myProp2}")
Log.d("MainActivity", "singleton randObject: ${Object.randObject}")
Log.d("MainActivity", "singleton randObject: ${Object.randObject.myProp}")
Log.d("MainActivity", "singleton randObject: ${Object.randObject.myProp2}")
}
}
Instance:
class Instance: AClass(){
override val testString: String = "test"
override val testUriString: String = "https://www.google.se"
override val testUri: Uri = Uri.parse(testUriString)!!
override val randObject: RandomObject = RandomObject("Herp")
}
Object
object Object : AClass(){
override val testString: String = "test"
override val testUriString: String = "https://www.google.se"
override val testUri: Uri = Uri.parse(testUriString)!!
override val randObject: RandomObject = RandomObject("Herp")
}
AClass:
abstract class AClass{
abstract val testString: String
abstract val testUriString: String
abstract val testUri: Uri
abstract val randObject: RandomObject
init {
Log.d("AClass", "testString: $testString")
Log.d("AClass", "testUriString: $testUriString")
Log.d("AClass", "testUri: $testUri")
Log.d("AClass", "randObject: $randObject")
}
}
Output:
D/AClass: testString: null
D/AClass: testUriString: null
D/AClass: testUri: null
D/AClass: randObject: null
D/MainActivity: instance randObject: com.technocreatives.abstracttest.RandomObject@4455b26
D/MainActivity: instance randObject: derp
D/MainActivity: instance randObject: Herp
D/AClass: testString: test
D/AClass: testUriString: https://www.google.se
D/AClass: testUri: null
D/AClass: randObject: null
D/MainActivity: singleton randObject: com.technocreatives.abstracttest.RandomObject@8b19367
D/MainActivity: singleton randObject: derp
D/MainActivity: singleton randObject: Herp
After this I came to the realization that overridden probably are not initialized until after the init{}
has been executed. But then I saw what happened when i created a singleton. The value testUriString
is set in the init
. Why is this the case? Is it a bug? What is the expected behaviour of singleton and override val?
I tried searching for the documentation but have not found any information about this in the documentation.