In this second episode of our learning Kotlin series, we talk about Kotlin’s support for static members or … lack thereof. Kotlin as a language was designed so that there’s no such thing as a “static member” in a class but there are times when having static members can be useful.
So what do we do in those cases? do we just avoid static members? are there better alternatives? what are the costs with some of these approaches?
Listen on to find out more!
Download directly
Show Notes
Static alternatives
Cost of approaches
Look at the end of these notes for code snippets
Misc:
Sponsors
Contact
Code snippets
Cost effectiveness
// ----------------------------------------
// THIS IS BAD
class Foo {
companion object {
val myVar = "testing"
}
}
// calling from Kotlin
Foo.myVar
// calling from Java
Foo.Companion.getMyVar(); // yuck
// ----------------------------------------
// THIS IS OK
// notice the Jvm annotation
class Foo {
companion object {
@JvmField val myVar = "testing"
}
}
// calling from Kotlin
Foo.myVar
// calling from Java
Foo.myVar;
// ----------------------------------------
// THIS IS AWESOME
// notice the const keyword
class Foo {
companion object {
const val myVar = "testing"
}
}
// calling from Kotlin
Foo.myVar
// calling from Java
Foo.myVar;
// compiler additionally inlines this
// myVar is not a primitive or String?
// use @JvmField or @JvmStatic for methods
Package level options
// inside BottomSheetView.Kt
class BottomSheetView {
companion object {
const val BOTTOM_SHEET_ANIMATION_TIMING = 500L
}
// ...
}
// accessed as:
animation.setTiming(BottomSheetView.BOTTOM_SHEET_ANIMATION_TIMING)
// ----------------------------------------
// INSTEAD DO THIS
// inside BottomSheetView.Kt
const val BOTTOM_SHEET_ANIMATION_TIMING = 500L
class BottomSheetView {
// ...
}
// accessed as:
animation.setTiming(BottomSheetViewKt.BOTTOM_SHEET_ANIMATION_TIMING)