I really had this exact question 30 minutes ago, so I started digging around and couldn't find any solution or workaround for this, BUT during the search I found this section on the Kotlinglang website that says:
Note that extensions can be defined with a nullable recipient type. Such extensions can be called on an object variable, even if its value is zero.
So, I had the craziest idea, why not define an extension function with a nullable receiver (without actually using this receiver), and then call it for a null object! I tried it, and it worked pretty well, but it looked so ugly. It was like this:
(null as Type?).staticFunction(param1, param2)
So I got around this by creating val in my extension type file of the receiver type with a value of null, and then using it in my other class. So, as an example, here's how I implemented the βstaticβ extension function for the Navigation class in Android: In my NavigationExtensions.kt file:
val SNavigation: Navigation? = null fun Navigation?.createNavigateOnClickListener(@IdRes resId: Int, args: Bundle? = null, navOptions: NavOptions? = null, navigationExtras: Navigator.Extras? = null) : (View) -> Unit {
In the code that uses this:
SNavigation.createNavigateOnClickListener(R.id.action_gameWonFragment_to_gameFragment)
Obviously, this is not a class name, it is just a class type variable that has a null value. This is obviously ugly on the creator side of the extension (because they must create the variable) and on the side of the developer (because they must use the SType format instead of the actual class name), but this is the closest that can be achieved correctly Now compared to real static functions . We hope that the creators of the Kotlin language will answer the created problem and add this function to the language.
kyay Jun 12 '19 at 4:08 2019-06-12 04:08
source share