- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Accessing Kotlin extension functions from Java
In Kotlin, you can easily call another function by just importing the same in the current Kotlin file where your main function is running. Whatever the function we are declaring in a Kotlin file will be compiled into a static method by default, and it will be placed under the same package. The name of the newly created file will be renamed as the First letter capitalized and ".kt" extension replaced with the "Kt" suffix.
In this article, we will try to get an insight into how you can use Kotlin extension methods from a Java file.
Example
Let's create a Kotlin file and name it as "myExt.kt" and place the following code inside it.
Package com.extension fun String.myFunc():String{ return "Welcome to Kotlin Extension File" }
Now we can easily access this extension in another Kotlin file by importing the same function, as shown below.
Package com.model // Using this import statement, // you can directly use this function // in another Kotlin function. import com.extension.myFunc
Now, our task is to use the function in the Java environment.
In the Java section, let's assume we have the following Java file and we want to use our previously generated extension method in the same.
Package com.service // The newly created file that can be accessed via JVM import com.extension.myExtKT public class MyClass { public static void main(String args[]) { System.out.println(myExtKT.myFunc();); } }
You can use your Kotlin Extension method directly using this newly static file create by the Kotlin compiler.
Output
Once the above piece of code is executed, it will generate the following output.
Welcome to Kotlin Extension File
- Related Articles
- How to call C++ functions from Java?
- Get file extension name in Java
- Accessing table data from SAP system
- Accessing a Java class in other package.
- Accessing variables of two interfaces, which are same from an implementing class in java?
- Accessing nth element from Python tuples in list
- How to raise Python exception from a C extension?
- Create temporary file with specified extension suffix in Java
- What is default, defender or extension method of Java 8?
- How MySQL prevents unauthorized clients from accessing the database system?
- Time Functions in Java
- Trigonometric Functions in Java
- Log functions in Java
- Iterator Functions in Java
- Calendar Functions in Java
