What is the equivalent of the following Java code in pure Kotlin?
Class.forName(className).newInstance()
Suppose we are in a Kotlin multi-platform project.
Similar to using the fun keyword in Kotlin to create a new function, use the class keyword to create a new class. You can choose any name for a class , but it is helpful if the name indicates what the class represents. By convention, the class name is written in Upper Camel Case (also called Pascal Casing).
To define a class in Kotlin, class keyword is used: class ClassName { // property // member function ... .. ... } Here, we defined a class named Lamp . The class has one property isOn (defined in same way as variable), and two member functions turnOn() and turnOff() .
Following is the syntax to create a Kotlin Class: A Kotlin class declaration is similar to Java Programmig which consists of a class header and a class body surrounded by curly braces. class ClassName { // Class Header // // Variables or data members // Member functions or Methods // ... ... }
Kotlin handles this case with object expressions and object declarations. Object expressions create objects of anonymous classes, that is, classes that aren't explicitly declared with the class declaration. Such classes are handy for one-time use. You can define them from scratch, inherit from existing classes, or implement interfaces.
Before you create objects in Kotlin, you need to define a class. A class is a blueprint for the object. We can think of class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object.
We can access the member function of the class using the object. Kotlin program of creating multiple objects and accessing the property and member function of class –
Kotlin does not have a new keyword. The process of creating instances of nested, inner, and anonymous inner classes is described in Nested classes. Classes can be derived from each other and form inheritance hierarchies. Learn more about inheritance in Kotlin. A class may be declared abstract, along with some or all of its members.
This will just work as-is in Kotlin on the JVM, as Kotlin is compiled to JVM classes which are available via Java reflection, so you can use this line of code in Kotlin as well.
For other Kotlin platforms (Kotlin/JS, Kotlin/Native), there's currently no proper reflection support, so you can't do that when running on those platforms.
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