I am trying to pass a class as an argument in Kotlin so that I can reuse a method, how would I convert this Java function to a Kotlin function?
public void goToActivity(Activity activity, Class classs) {
Intent intent = new Intent(activity, classs);
context.startActivity(intent);
activity.finish();
}
In Kotlin, a function which can accept a function as parameter or can return a function is called Higher-Order function. Instead of Integer, String or Array as a parameter to function, we will pass anonymous function or lambdas. Frequently, lambdas are passed as parameter in Kotlin functions for the convenience.
Unit in Kotlin corresponds to the void in Java. Like void, Unit is the return type of any function that does not return any meaningful value, and it is optional to mention the Unit as the return type. But unlike void, Unit is a real class (Singleton) with only one instance.
In Kotlin, all classes are final by default. To permit the derived class to inherit from the base class, we must use the open keyword in front of the base class. Kotlin Inheriting property and methods from base class: When we inherit a class then all the properties and functions are also inherited.
We can use the library function arrayOf() to create an array by passing the values of the elements to the function. Since Array is a class in Kotlin, we can also use the Array constructor to create an array. The constructor takes two parameters: The size of the array, and.
A class is passed in this format in Kotlin ClassName::class.java
.
This seems to be the correct way to do it:
fun Context.goToActivity(activity: Activity, classs: Class<*>?) {
val intent = Intent(activity, classs)
startActivity(intent)
activity.finish()
}
And an example of how the method is called:
goToActivity(this, OneMainActivity::class.java)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With