Java To Kotlin : Manual Steps to convert the code

Bhoomi Vaghasiya Gadhiya
4 min readJul 17, 2023

--

In the 2017 Google I/O conference, Kotlin was announced as an official language for Android app development. it is a powerful and versatile language that is well-suited for a variety of development tasks. Also, Kotlin is interoperable with Java, making it easy to convert existing Java code to Kotlin.

There are many methods that convert Java to Kotlin automatically, but the generated Kotlin code may not always be perfect or idiomatic. Manual intervention is often required to improve the quality and readability of the code. In this Article, we will discuss the manual steps to convert Java code to Kotlin.

Steps:

Nullability:

Kotlin has built-in null safety features. Review the converted code and use the nullable (?) or non-null (!!) operators appropriately to indicate nullability of variables and function return types. Here’s an example of how nullability can be handled in Kotlin:

//Java
String getName() {
if (someCondition()) {
return "John Doe";
} else {
return null;
}
}
//Kotlin
fun getName(): String? {
return if (someCondition()) {
"John Doe"
} else {
null
}
}

Type inference:

Kotlin has improved type inference compared to Java. Look for explicit type declarations in the converted code and consider removing them where the type can be inferred by the compiler.

//Java
String message = "Hello, Kotlin!";
//Kotlin
val message = "Hello, Kotlin!"

Immutable variables:

In Kotlin, it’s common to use val or immutable variables instead of var. Identify variables that are intended to be read-only and change their declaration to val. Here’s an example of type inference:

//Java
String message = "Hello";
message = "Goodbye"; // Reassignment is allowed
//Kotlin
val message = "Hello"
message = "Goodbye" // Compilation error: Val cannot be reassigned

Properties (Getter/Setter):

In Kotlin, you can use properties, which provide a more concise syntax than Java. Replace Java-style getters and setters with Kotlin properties wherever appropriate. Here’s an example of using properties:

//Java
public class Person {
private String name;

public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
}
//Kotlin
class Person {
var name: String = ""
get() = field
set(newName) {
field = newName
}
}

Replace static methods:

Kotlin does not have static methods like Java. Convert static methods to top-level functions or companion object functions.

//Java
public class MathUtils {
public static int add(int a, int b) {
return a + b;
}
}
//Kotlin
class MathUtils {
companion object {
fun add(a: Int, b: Int): Int {
return a + b
}
}
}

Use extension functions:

Kotlin allows you to define extension functions that add new functionality to existing classes. Identify utility methods in Java and declare the extension function with the desired class as the receiver type, allowing you to call the function as if it were a member function of that class.

//Java
public class StringUtil {
public static String capitalizeFirstLetter(String input) {
if (input == null || input.isEmpty()) {
return input;
}
return input.substring(0, 1).toUpperCase() + input.substring(1);
}
}

String name = "Bhoomi Vaghasiya";
String capitalized = StringUtil.capitalizeFirstLetter(name); // "Bhoomi Vaghasiya"
//Kotlin
fun String.capitalizeFirstLetter(): String {
if (isNullOrEmpty()) {
return this
}
return substring(0, 1).toUpperCase() + substring(1)
}

val name = "Bhoomi Vaghasiya"
val capitalized = name.capitalizeFirstLetter() // "Bhoomi Vaghasiya"

String concatenation:

Replace string concatenation with string interpolation using the “$” symbol or by using the ‘format’ function. Here’s an example:

//Java
String firstName = "Bhoomi";
String lastName = "Vaghasiya";
String fullName = firstName + " " + lastName;
//Kotlin
val firstName = "Bhoomi"
val lastName = "Vaghasiya"
val fullName = "$firstName $lastName"

Java-specific libraries:

If the converted code relies on Java-specific libraries, consider replacing them with Kotlin equivalents or more idiomatic Kotlin libraries to ensure compatibility and take advantage of Kotlin’s language features. Here’s an example:

Java-specific library: java.util.Date

Kotlin’s library: java.time.LocalDate

Kotlin standard library functions:

Kotlin provides many utility functions in its standard library such as string manipulation, collections processing, file handling, and more. Utilizing these standard library functions simplifies the code and improves readability. Here’s an example of using Kotlin standard library functions:

//Kotlin
val str = "hello, kotlin!"

// Length of the string
val length = str.length

// Check if the string starts with a specific prefix
val startsWithHello = str.startsWith("hello")

// Convert the string to uppercase
val uppercaseStr = str.toUpperCase()

// Split the string into a list of substrings
val substrings = str.split(", ")

Review naming conventions:

Kotlin follows different naming conventions compared to Java. Ensure that variable names, method names, and class names follow Kotlin’s naming conventions. Here’s an example of naming convention changes:

//Java
public class MyUtils {
private int myVariable;

public void doSomething() {
// Code implementation
}
}
//Kotlin
class MyUtils {
private var myVariable: Int = 0

fun doSomething() {
// Code implementation
}
}

Use Kotlin idioms:

Familiarize yourself with Kotlin idiomatic patterns, such as if expressions, when statements, functional programming constructs, and the use of Kotlin’s collections API. Here’s an example of using Kotlin idioms:

//Kotlin
val num = 5

// Traditional if-else statement
val result = if (num > 0) {
"Positive"
} else {
"Non-positive"
}

// Kotlin idiomatic if expression
val result = if (num > 0) "Positive" else "Non-positive"

It’s essential to review and test the converted code thoroughly to ensure it functions correctly after the manual modifications. By following the manual steps outlined in this article, developers can ensure a smooth transition from Java to Kotlin.

Thanks for reading this article! Leave a comment below if you have any questions.

If you have any query related to Android, I’m always happy to help you. You can reach me on Twitter and LinkedIn.

--

--

Bhoomi Vaghasiya Gadhiya

Android Developer 📱 | Enthusiastic about helping others 🤝 | | Let's code to create a better world! 🌟