Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a class to a function in Kotlin

Tags:

java

kotlin

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();
}
like image 963
Kaita John Avatar asked Jun 02 '20 03:06

Kaita John


People also ask

How do you pass a function in Kotlin?

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.

What is () -> unit in Kotlin?

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.

How do I inherit a class in Kotlin?

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.

How do you pass an array to a function in Kotlin?

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.


1 Answers

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)
like image 128
Kaita John Avatar answered Nov 15 '22 01:11

Kaita John