Java to Kotlin Reference
by Riley MacDonald, December 22, 2017

A quick reference of how code written in Java is written in Kotlin.

Variable Declaration (final and non final)

Java

1
2
3
4
// non final
String name = "Riley MacDonald";
// final
final String name = "Riley MacDonald";

Kotlin

1
2
3
4
// non final
var name = "Riley MacDonald"
// final
val name = "Riley MacDonald"

Nullable Variables

Java

1
2
String nullableString;
nullable = null;

Kotlin

1
2
var nullableInt: Int?
nullable = null

Null Checks

Java

1
2
3
if (nullableInt != null) {
    Int anotherInt = nullable;
}

Kotlin

1
2
3
4
5
nullableInt.let {
    var anotherInt = nullableInt
}
// simplified
var anotherInt = nullableInt?

String Formatting / Referencing

Java

1
2
3
final String one = "one";
final String two = "two";
System.out.println(String.format("Counting: %s, %s", one, two)); // Counting: one, two

Kotlin

1
2
3
val one = "one"
val two = "two"
println("Counting: $one, $two") // Counting: one, two

Multi-Line Strings

Java

1
2
3
final String multilineString = "line one\n" +
                               "line two\n" +
                               "line three\n";

Kotlin

1
2
3
4
5
val text = """
        |line one
        |line two
        |line three
        """.trimMargin()

Casting and Cast Validation

Java

1
2
3
4
5
6
// Validation / null check
if (object instanceOf Cat) {
    if (object != null) {
        Cat cat = (Cat) object;
    }
}

Kotlin

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Validation
if (object is Cat) {
    // declared cast
    var cat = object as Cat
    // smart casting
    var cat = object
}
 
// null checks
if (object is Cat?) {
    var car = object // null if object is null
}
 
var cat = object as? Cat
// or
var cat = object as Cat?

Conditional Ranges

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// If
if (value >= 0 && value <= 250) { }
 
// Switch
boolean result;
switch (value) {
    case 20: 
        result = true;
        break;
    case 233:
    case 234:
        result = true;
        break;
    default: 
        result = false;
}

Kotlin

1
2
3
4
5
6
7
8
9
10
// If
if (value in 0..250) { }
 
// When
var result = when(value) {
    20 -> true
    233,234 -> true
    else -> false
    // ranges such as `in 5..10 ->` also supported
}

Loops

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// range loop
for (int i = 0; i <= 200; i++) { }
 
// list
for (Cat cat : catList) { 
    if (cat.canMeow()) cat.meow();
}
 
// map entry set
for (Map.Entry<String, String> thing : map.entrySet()) { }
 
// Java 8
list.forEach(cat -> cat.meow());
list.stream().filter(cat -> cat.canMeow()).forEach(cat -> cat.meow());

Kotlin

1
2
3
4
5
6
7
8
9
10
11
// range loop
for (i in 0..200) { }
 
// list
for (cat in catList) { }
 
// list filtering
catList.filter { it.canMeow() }.forEach { it.meow() }
 
// map entry set
for ((key, value) in map) { }

Populating Collections

Java

1
2
3
4
5
6
7
8
// list
final List<String> listOfStrings = Arrays.toList("one", "two", "three");
 
// map
final Map<String, String> mapOfStrings = new HashMap<String, String>();
mapOfStrings.put("oneKey", "oneValue");
mapOfStrings.put("twoKey", "twoValue");
mapOfStrings.put("threeKey", "threeValue");

Kotlin

1
2
3
4
5
6
7
// list
val listOfStrings = listOf("one", "two", "three")
 
// map
val mapOfStrings = mapOf("oneKey" to "oneValue",
                         "twoKey" to "twoValue",
                         "threeKey" to "threeValue")

String Splitting

Java

1
2
3
4
String cat = "cat=orange";
String [] split = cat.split("=");
String param = split[0];
String value = split[1];

Kotlin

1
2
val cat = "cat=orange"
val (param, value) = cat.split("=")

Functions

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// public function
public void doThing() { }
 
// private function
private void doAnotherThing() { }
 
// varargs
void doThings(String... strings) { }
 
// returns
String getString() {
    return "string";
}
 
// args
String getString(String append) {
    return append + " string";
}
 
// package private
int getInt() {
    return 1;
}

Kotlin

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// public function
fun doThing() { }
 
// private function
private fun doAnotherThing() { }
 
// varargs
fun doThing(vararg string: String) { }
 
// returns
fun doThing(): String {
    return "string"
}
 
// args
fun getString(append: String) {
    return "$append string"
}
// or
fun getString(append: String): String = "$append string"
// or
fun getString(append: String) = "$append string" // automatically determines type
 
// package private (Kotlin also has protected)
internal fun getInt() {
    return 1
}

Classes

Java

1
2
3
4
5
6
7
8
// Class with private constructor and static method
public class Example {
    private Example() { }
 
    public static String getString() {
        return "string";
    }
}

Kotlin

1
2
3
4
5
6
7
8
9
10
// Class with private constructor and static method
class Example private constructor() {
    companion object {
        fun getString() = "string"
    }
}
// if all methods are static
object Example {
    fun getString() = "string"
}

Setting Object Values

Java

1
2
3
4
Something something = new Something();
something.firstVal(1);
something.secondVal(2);
something.thirdVal(3);

Kotlin

1
2
3
4
5
6
7
8
9
10
11
12
13
14
val something = Something()
 
with(something) {
    firstVal = 1
    secondVal = 2
    thirdVal = 3
}
 
// or
something.apply {
    firstVal = 1
    secondVal = 2
    thirdVal = 3
}.create()

Value Classes

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class Example {
    public String string;
 
    public Example(String string) {
 
    }
 
    public String getString() {
        return string;
    }
 
    public void setString(String string) {
        this.string = string;
    }
 
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
 
        Example example = (Example) o;
 
        return string != null ? string.equals(example.string) : example.string == null;
    }
 
    @Override
    public int hashCode() {
        return string != null ? string.hashCode() : 0;
    }
 
    @Override
    public String toString() {
        return "Example{" +
                "string='" + string + '\'' +
                '}';
    }
}

Kotlin

1
data class Example(var string: String)

Consuming Kotlin Default Parameters in Java
There’s two ways to consume Kotlin functions containing default parameters using Java:

  • Call the function providing all arguments (whether they’re default or not).
  • Annotate the Kotlin method with the @JvmOverloads annotation. This tells the compiler to generate overloaded methods for each of the possible combination or parameters.

Writing and Consuming “Static” Kotlin methods in Java
Kotlin doesn’t have a static keyword but you can still achieve the same functionality by writing methods outside of a class declaration. Methods written outside of a class declaration will be compiled as static methods which can be referenced by the file name in Java. If desired you can declare the class name to be compiled using the @file:JvmName annotation. For example:

1
2
3
4
5
6
7
8
9
// File name Log.kt
 
@file:JvmName("Logger")
 
package your.package.name
 
fun printMessage(message: String) {
  println(message)
}

Which is compiled to the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package your.package.name;
 
import java.io.PrintStream;
import kotlin.Metadata;
import kotlin.jvm.JvmName;
import kotlin.jvm.internal.Intrinsics;
import org.jetbrains.annotations.NotNull;
 
@Metadata(mv={1, 1, 13}, bv={1, 0, 3}, k=2, d1={"\000\f\n\000\n\002\020\002\n\000\n\002\020\016\032\016\020\000\032\0020\0012\006\020\002\032\0020\003"}, d2={"printMessage", "", "message", ""})
@JvmName(name="Logger")
public final class Logger
{
  public static final void printMessage(@NotNull String message)
  {
    Intrinsics.checkParameterIsNotNull(message, "message");System.out.println(message);
  }
}

Which can be consumed by Java using:

1
2
String message = "Hello World";
Logger.printMessage(message);
Open the comment form

Leave a comment:

Comments will be reviewed before they are posted.

User Comments:

Be the first to leave a comment on this post!