- Java to Kotlin File Conversion
- Use IntelliJ IDEA – Convert Java File to Kotlin File
- Try Online “Convert from Java”
- Conclusion
- Related Tutorials
- Конвертер java to kotlin
- Key differences between Java and Kotlin
- Конвертер java to kotlin
- Convert Java to Kotlin using the Community Edition of IntelliJ
- Converting Code from Java to Kotlin
- Java vs Kotlin
- General Observations
Java to Kotlin File Conversion
Many projects and applications are coded using Java programming language. In a Kotlin application, you can have Java files along with Kotlin files. But, if you like to convert your Java code to Kotlin code, you may do so.
To migrate from Java to Kotlin, Kotlin Official is providing tools via online, which is using official Kotlin site, or offline, which is using IntelliJ IDEA integrated development environment.
A quick route for the above said methods is given below.
- Use IntelliJ IDEA Main menu -> Code -> Convert Java File to Kotlin File
- You can use the online converter from Kotlin Official Website. https://try.kotlinlang.org/ -> Convert from Java
Of course, we shall go in detail using a step by step process and screenshots to better understand the process to convert Java code to Kotlin code.
Note: If you are using IntelliJ IDEA or any other IDE with Kotlin Plugin, you can write Kotlin code along with Java code in the same .kt file.
Use IntelliJ IDEA – Convert Java File to Kotlin File
IntelliJ IDEA is an Integrated Development Environment by JetBrains.
Following are the steps to convert your Java File to Kotlin File using IntelliJ IDEA,
Step 1: Open your Project in IntelliJ IDEA, and open the Java file.
Step 2: In the main menu bar, click on “Code”. Click on the item “Convert Java File to Kotlin File”
Step 3: If you get a message “Some code in the rest of your project may require corrections after performing this conversion. Do you still want to find such code and correct it too?”, you may click OK.
Step 4: Finally, your Java file is converted to a Kotlin file. Try running it.
Try Online “Convert from Java”
Step 1: Hit the URL “https://try.kotlinlang.org/” in your favorite browser and click on “Convert from Java” button, highlighted in the below picture.
Step 2: Paste you Java Code in the left editor box and click on “Convert to Kotlin” button present in the bottom right corner of the window.
Conclusion
In this Kotlin Tutorial, we learned how to convert Java File to Kotlin File.
If you are doing Android application development using Kotlin, you may refer how to convert Java File in Android application to Kotlin File.
Related Tutorials
Конвертер java to kotlin
This free online converter lets you convert code from Java to Kotlin in a click of a button. To use this converter, take the following steps —
- Type or paste your Java code in the input box.
- Click the convert button.
- The resulting Kotlin code from the conversion will be displayed in the output box.
Key differences between Java and Kotlin
Characteristic | Java | Kotlin |
---|---|---|
Syntax | Java has a verbose syntax with a lot of boilerplate code, whereas Kotlin has a concise and expressive syntax that reduces the amount of code needed to accomplish the same task. | Kotlin has a concise and expressive syntax that reduces the amount of code needed to accomplish the same task compared to Java. |
Paradigm | Java is an object-oriented programming language that supports imperative and declarative programming paradigms, whereas Kotlin is a statically-typed programming language that supports both object-oriented and functional programming paradigms. | Kotlin is a statically-typed programming language that supports both object-oriented and functional programming paradigms. |
Typing | Java is a statically-typed language, which means that the type of a variable is determined at compile-time, whereas Kotlin is also a statically-typed language but supports type inference, which means that the type of a variable can be inferred by the compiler. | Kotlin is a statically-typed language that supports type inference, which means that the type of a variable can be inferred by the compiler. |
Performance | Java has a reputation for being fast and efficient due to its Just-In-Time (JIT) compiler, which compiles bytecode into machine code at runtime. Kotlin also has good performance, but it is slightly slower than Java due to its additional features. | Kotlin has good performance, but it is slightly slower than Java due to its additional features. |
Libraries and frameworks | Java has a vast collection of libraries and frameworks, including Spring, Hibernate, and Struts, which are widely used in enterprise applications. Kotlin can also use these libraries and frameworks, but it also has its own set of libraries and frameworks, such as Ktor and Anko. | Kotlin can use Java’s vast collection of libraries and frameworks, but it also has its own set of libraries and frameworks, such as Ktor and Anko. |
Community and support | Java has a large and active community with a wealth of resources and support available, including documentation, forums, and tutorials. Kotlin’s community is growing rapidly, but it is still smaller than Java’s. | Kotlin’s community is growing rapidly, but it is still smaller than Java’s. However, there are still a wealth of resources and support available, including documentation, forums, and tutorials. |
Learning curve | Java has a steep learning curve due to its verbose syntax and complex concepts, such as object-oriented programming and memory management. Kotlin has a much gentler learning curve due to its concise syntax and ease of use. | Kotlin has a much gentler learning curve than Java due to its concise syntax and ease of use. |
Конвертер java to kotlin
System.out.print("Hello, World!"); System.out.println("Hello, World!");
print("Hello, World!") println("Hello, World!")
final int x; final int y = 1;
var w: Int var z = 2 z = 3 w = 1
final String name = null; String lastName; lastName = null
val name: String? = null var lastName: String? lastName = null var firstName: String firstName = null // Compilation error!!
val length = text?.length val length = text. length // NullPointerException if text == null
String name = "John"; String lastName = "Smith"; String text = "My name is: " + name + " " + lastName; String otherText = "My name is: " + name.substring(2);
val name = "John" val lastName = "Smith" val text = "My name is: $name $lastName" val otherText = "My name is: $"
String text = "First Line\n" + "Second Line\n" + "Third Line";
val text = """ |First Line |Second Line |Third Line """.trimMargin()
String text = x > 5 ? "x > 5" : "x
val text = if (x > 5) "x > 5" else "x
final int andResult = a & b; final int orResult = a | b; final int xorResult = a ^ b; final int rightShift = a >> 2; final int leftShift = a
val andResult = a and b val orResult = a or b val xorResult = a xor b val rightShift = a shr 2 val leftShift = a shl 2
if(x instanceof Integer) < >final String text = (String) other; if(x >= 0 && x
if (x is Int) < >val text = other as String if (x in 0..10)
final int x = // value; final String xResult; switch (x) < case 0: case 11: xResult = "0 or 11"; break; case 1: case 2: //. case 10: xResult = "from 1 to 10"; break; default: if(x < 12 && x >14) < xResult = "not from 12 to 14"; break; >if(isOdd(x)) < xResult = "is odd"; break; >xResult = "otherwise"; > final int y = // value; final String yResult; if(isNegative(y)) < yResult = "is Negative"; >else if(isZero(y))< yResult = "is Zero"; >else if(isOdd(y))< yResult = "is Odd"; >else
val x = // value val xResult = when (x) < 0, 11 ->"0 or 11" in 1..10 -> "from 1 to 10" !in 12..14 -> "not from 12 to 14" else -> if (isOdd(x)) < "is odd" >else < "otherwise" >> val y = // value val yResult = when < isNegative(y) ->"is Negative" isZero(y) -> "is Zero" isOdd(y) -> "is odd" else -> "otherwise" >
for (int i = 1; i < 11 ; i++) < >for (int i = 1; i < 11 ; i+=2) < >for (String item : collection) < >for (Map.Entry<String, String> entry: map.entrySet())
for (i in 1 until 11) < >for (i in 1..10 step 2) <> for (item in collection) <> for ((index, item) in collection.withIndex()) <> for ((key, value) in map) <>
final List<Integer> numbers = Arrays.asList(1, 2, 3); final Map<Integer, String> map = new HashMap<Integer, String>(); map.put(1, "One"); map.put(2, "Two"); map.put(3, "Three"); // Java 9 final List<Integer> numbers = List.of(1, 2, 3); final Map<Integer, String> map = Map.of(1, "One", 2, "Two", 3, "Three");
val numbers = listOf(1, 2, 3) val map = mapOf(1 to "One", 2 to "Two", 3 to "Three")
for (int number : numbers) < System.out.println(number); >for (int number : numbers) < if(number >5) < System.out.println(number); >>
numbers.forEach < println(it) >numbers.filter < it >5 > .forEach
final Map<String, List<Integer>> groups = new HashMap<>(); for (int number : numbers) < if((number & 1) == 0)< if(!groups.containsKey("even"))< groups.put("even", new ArrayList<>()); > groups.get("even").add(number); continue; > if(!groups.containsKey("odd"))< groups.put("odd", new ArrayList<>()); > groups.get("odd").add(number); > // or Map> groups = items.stream().collect( Collectors.groupingBy(item -> (item & 1) == 0 ? "even" : "odd") );
val groups = numbers.groupBy
final List<Integer> evens = new ArrayList<>(); final List<Integer> odds = new ArrayList<>(); for (int number : numbers)< if ((number & 1) == 0) < evens.add(number); >else < odds.add(number); >>
val (evens, odds) = numbers.partition
final List<User> users = getUsers(); Collections.sort(users, new Comparator<User>() < public int compare(User user, User otherUser)< return user.lastname.compareTo(otherUser.lastname); >>); // or users.sort(Comparator.comparing(user -> user.lastname));
val users = getUsers() users.sortedBy
Convert Java to Kotlin using the Community Edition of IntelliJ
I'm going to convert Java to Kotlin using the Community Edition of IntelliJ (2021.3.2). We'll look at the differences from the perspective of a Java developer. The Java sample is from University of Texas: Java samples specifically this one: UnsortedHashSet sample
Converting Code from Java to Kotlin
I'll start by creating a new Kotlin project:
I am creating a new Kotlin file called UnsortedHashSet inside of this new project.
I am now copy-pasting the java code from UnsortedHashSet Java sample into this file.
This automatically brings up a popup and asks if I want to convert the Java code to Kotlin.
I obviously click on "Yes". This code segment is auto-created:
import java.util.* class UnsortedHashSet < private var size = 0 private var con: Array init < con = arrayOfNulls?>(10) as Array > fun add(obj: E): Boolean < val oldSize = size val index = Math.abs(obj.hashCode()) % con.size if (con[index] == null) con[index] = LinkedList() if (!con[index]. contains(obj)) < con[index]. add(obj) size++ >if (1.0 * size / con.size > LOAD_FACTOR_LIMIT) resize() return oldSize != size > private fun resize() < val temp = UnsortedHashSet() temp.con = arrayOfNulls?>(con.size * 2 + 1) as Array for (i in con.indices) < if (con[i] != null) for (e in con[i]!!) temp.add(e) >con = temp.con > fun size(): Int < return size >companion object < private const val LOAD_FACTOR_LIMIT = 0.7 >>
fun main(args: Array) < println("Hello World!") var ush = UnsortedHashSet() ush.add("Hannu Goiss") ush.add("Test Name") ush.add("another name") println("ush size: " + ush.size()) >
Hello World! ush size: 3 Process finished with exit code 0
Java vs Kotlin
private static final double LOAD_FACTOR_LIMIT = 0.7; private int size; private LinkedList[] con;
private var size = 0 private var con: Array?>
- We don't need the ";"
- In Kotlin there is a difference between var and val. Val is used for the static value. Interestingly the converter is later using val for Java variables as well and can to figure out that those contain values that are never changing.
2. The Constructor
Java Code:
public UnsortedHashSet() < con = (LinkedList[])(new LinkedList[10]); >
Observations:
We could have probably written more compact code: Declaring Classes in Kotlin
3. The "add" function
Java Code:
public boolean add(E obj) < int oldSize = size; int index = Math.abs(obj.hashCode()) % con.length; if(con[index] == null) con[index] = new LinkedList(); if(!con[index].contains(obj)) < con[index].add(obj); size++; >if(1.0 * size / con.length > LOAD_FACTOR_LIMIT) resize(); return oldSize != size; >
fun add(obj: E): Boolean < val oldSize = size val index = Math.abs(obj.hashCode()) % con.size if (con[index] == null) con[index] = LinkedList() if (!con[index]. contains(obj)) < con[index]. add(obj) size++ >if (1.0 * size / con.size > LOAD_FACTOR_LIMIT) resize() return oldSize != size >
Observations:
oldSize and index are declared as val and not as var. This is good, as both values never change.
4. The "resize" function
Java Code:
private void resize() < UnsortedHashSettemp = new UnsortedHashSet(); temp.con = (LinkedList[])(new LinkedList[con.length * 2 + 1]); for(int i = 0; i < con.length; i++)< if(con[i] != null) for(E e : con[i]) temp.add(e); >con = temp.con; >
private fun resize() < val temp = UnsortedHashSet() temp.con = arrayOfNulls?>(con.size * 2 + 1) as Array for (i in con.indices) < if (con[i] != null) for (e in con[i]!!) temp.add(e) >con = temp.con >
- the for-loop has a different syntax. But in general, it looks similar.
- arrayOfNulls is definitely something new!
- !! is an interesting way to access one element in an array.
- the syntax with . as . is something to get used to.
5. The "size" function
Java Code:
Observations:
This function didn't change much, except the slightly different syntax.
General Observations
- 44 lines of code reduced to 39. those reductions are mainly due to different syntax for control structures. If we would be manually creating this code, we could have written much more compact code.
- The syntax is different, so it requires some adjustment when creating code. But the syntax is so similar, that reading the code is easy. New concepts like "!!" are easy to understand at first glance.
The following link gives an overview of differences between Kotlin and Java (Java vs Kotlin) and the issues addressed in Kotlin. One key selling point is interoperability.
When you learn a new programming language, never just blindly convert code. You might create new issues: DON'T DO THIS
But it's for sure a good way to look at differences and get to know Kotlin.
I'm looking forward to coding in Kotlin.