All skills
kotlin avatar

/kotlin-tooling-java-to-kotlin

@8fc58af official
by kotlinkotlin/kotlin-agent-skills1.1k stars
42

Use when converting Java source files to idiomatic Kotlin, when user mentions "java to kotlin", "j2k", "convert java", "migrate java to kotlin", or when working with .java files that need to become .kt files. Handles framework-aware conversion for Spring, Lombok, Hibernate, Jackson, Micronaut, Quarkus, Dagger/Hilt, RxJava, JUnit, Guice, Retrofit, and Mockito.

Use this Skill: https://skilld.dev/gh/kotlin/kotlin-agent-skills/kotlin-tooling-java-to-kotlin

This session only. Nothing lands on disk.

referencesKNOWN-ISSUES.md

≈2.4k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Known Issues and Common Pitfalls

A reference of common issues encountered during Java-to-Kotlin conversion, with solutions.

Kotlin Keyword Conflicts

Java identifiers that are reserved keywords in Kotlin will cause compilation errors after conversion.

Affected keywords: when, in, is, object, fun, val, var, typealias, as

Solution: Backtick-escape them in Kotlin:

// Java
public void when(String event) { ... }
public boolean in(List<String> items) { ... }
// Kotlin — backtick-escaped
fun `when`(event: String) { ... }
fun `in`(items: List<String>): Boolean { ... }

When the API is internal (not exposed to other modules), prefer renaming the identifier to a non-keyword alternative instead of using backticks. For example, rename when to onEvent or in to contains.

SAM Conversion Ambiguity

When a Java method has overloads that each accept a different SAM (Single Abstract Method) interface, Kotlin's trailing lambda syntax becomes ambiguous. The compiler cannot determine which SAM interface the lambda should implement.

// Java — overloaded method accepting different SAM types
public class TaskExecutor {
    void submit(Runnable task) { ... }
    void submit(Callable<String> task) { ... }
}
// Kotlin — WRONG: ambiguous, won't compile
executor.submit { doWork() }

// Kotlin — CORRECT: explicit SAM constructor
executor.submit(Runnable { doWork() })
executor.submit(Callable { computeResult() })

Use explicit SAM constructor calls whenever there are overloaded methods accepting different functional interfaces.

Platform Types

Java types without nullability annotations (@Nullable, @NotNull, @NonNull) become "platform types" (T!) in Kotlin. Platform types bypass Kotlin's null-safety system — they are neither nullable nor non-null, and null checks are deferred to runtime.

// Java — no nullability annotations
public String getName() { return name; }
public List<String> getItems() { return items; }
// Kotlin — BAD: platform types left in converted code
val name = obj.name       // inferred as String! — unsafe
val items = obj.items     // inferred as List<String!>! — unsafe

// Kotlin — GOOD: explicit nullability based on code analysis
val name: String = obj.name              // if provably non-null
val name: String? = obj.name             // if could be null
val items: List<String> = obj.items      // if neither list nor elements are null

Always add explicit type declarations to eliminate platform types. Analyze the Java source code, documentation, and call sites to determine the correct nullability.

@JvmStatic / @JvmField / @JvmOverloads

When converted Kotlin code is still called from Java, use JVM interop annotations to maintain a clean Java API:

@JvmStatic — Makes companion object functions accessible as static methods from Java:

class Config {
    companion object {
        @JvmStatic
        fun getInstance(): Config = ...
    }
}
// Java callers can use: Config.getInstance()
// Without @JvmStatic they would need: Config.Companion.getInstance()

@JvmField — Exposes a property as a direct field rather than through getter/setter:

class Constants {
    companion object {
        @JvmField
        val DEFAULT_TIMEOUT = 30_000L
    }
}
// Java callers can use: Constants.DEFAULT_TIMEOUT
// Without @JvmField they would need: Constants.Companion.getDEFAULT_TIMEOUT()

@JvmOverloads — Generates Java overloads for functions with default parameters:

@JvmOverloads
fun connect(host: String, port: Int = 443, secure: Boolean = true) { ... }
// Java sees three overloads:
// connect(String host)
// connect(String host, int port)
// connect(String host, int port, boolean secure)

Checked Exceptions

Kotlin does not have checked exceptions. When Kotlin code is called from Java, the Java compiler will not know about thrown exceptions unless annotated with @Throws:

// Without @Throws, Java callers cannot catch IOException in a catch block
// (the Java compiler will say "exception is never thrown in the corresponding try block")

@Throws(IOException::class)
fun readFile(path: String): String {
    return File(path).readText()
}

Add @Throws to every Kotlin function that throws checked exceptions and is called from Java code.

Wildcard Generics

Java wildcard types map to Kotlin's variance annotations:

Java Kotlin Description
? extends T out T Covariance (producer)
? super T in T Contravariance (consumer)
Raw type List List<Any?> Add explicit type parameter
// Java
public void process(List<? extends Number> numbers) { ... }
public void addAll(List<? super Integer> target) { ... }
public void legacy(List items) { ... }  // raw type
// Kotlin
fun process(numbers: List<out Number>) { ... }
fun addAll(target: MutableList<in Int>) { ... }
fun legacy(items: List<Any?>) { ... }  // explicit type parameter

For raw types, analyze the code to determine the most specific type parameter rather than defaulting to Any?.

Static Members

Java's static keyword has no direct equivalent in Kotlin. Use the following mappings:

Static methods — Use companion object functions, or top-level functions if they don't need class state:

// Java
public class StringUtils {
    public static String capitalize(String s) { ... }
}
// Kotlin — top-level function (preferred when no class state needed)
fun capitalize(s: String): String { ... }

// Kotlin — companion object (when logically tied to the class)
class StringUtils {
    companion object {
        fun capitalize(s: String): String { ... }
    }
}

Static constants — Use const val for compile-time constants (primitives and String), val for object constants:

class HttpStatus {
    companion object {
        const val OK = 200                        // primitive — const val
        const val NOT_FOUND_MESSAGE = "Not Found" // String — const val
        val DEFAULT_HEADERS = mapOf("Accept" to "application/json") // object — val
    }
}

Static initializers — Use companion object init {} block or top-level code:

class Registry {
    companion object {
        private val handlers = mutableMapOf<String, Handler>()
        init {
            handlers["default"] = DefaultHandler()
        }
    }
}

Synchronized Blocks

Java's synchronized constructs map to Kotlin as follows:

Synchronized blocks — Use Kotlin's synchronized() function:

// Java
synchronized (lock) {
    sharedState.update();
}
// Kotlin
synchronized(lock) {
    sharedState.update()
}

Synchronized methods — Use the @Synchronized annotation:

// Java
public synchronized void update() { ... }
// Kotlin
@Synchronized
fun update() { ... }

Anonymous Inner Classes

Single Abstract Method (SAM) interfaces — Convert to lambda syntax:

// Java
executor.submit(new Runnable() {
    @Override
    public void run() {
        doWork();
    }
});
// Kotlin
executor.submit(Runnable { doWork() })

Multiple methods or abstract classes — Use object expression:

// Java
view.addListener(new ViewListener() {
    @Override
    public void onOpen() { ... }
    @Override
    public void onClose() { ... }
});
// Kotlin
view.addListener(object : ViewListener {
    override fun onOpen() { ... }
    override fun onClose() { ... }
})

Array Handling

Java arrays map to Kotlin types as follows:

Java Kotlin Notes
String[] Array<String> Reference type arrays
int[] IntArray Primitive array (not Array<Int>)
long[] LongArray Primitive array
double[] DoubleArray Primitive array
boolean[] BooleanArray Primitive array
Object[] Array<Any?>
new int[10] IntArray(10) Array creation
new String[10] arrayOfNulls<String>(10) Nullable element array
String... args vararg args: String Varargs parameter

Using Array<Int> instead of IntArray causes boxing overhead — always use the specialized primitive array types.

Ternary Operator

Kotlin has no ternary operator. Use if/else as an expression:

// Java
String label = (count > 0) ? "Items: " + count : "Empty";
// Kotlin
val label = if (count > 0) "Items: $count" else "Empty"

instanceof

Java's instanceof maps to Kotlin's is keyword. Kotlin supports smart casting, so an explicit cast after an is check is unnecessary:

// Java
if (shape instanceof Circle) {
    Circle circle = (Circle) shape;
    double area = circle.getArea();
}
// Kotlin — smart cast, no explicit cast needed
if (shape is Circle) {
    val area = shape.area  // shape is automatically cast to Circle
}

try-with-resources

Java's try-with-resources maps to Kotlin's .use {} extension function:

// Java
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
    String line = reader.readLine();
    process(line);
}
// Kotlin
BufferedReader(FileReader(path)).use { reader ->
    val line = reader.readLine()
    process(line)
}

The .use {} function works on any Closeable or AutoCloseable instance and guarantees the resource is closed even if an exception is thrown.

Source: SKILL.md on GitHub

No alerts16d4 checks · Risk SAFE
  • Gen Agent Trust Hub16d

    This skill provides a methodology for converting Java source code to Kotlin. While the logic is sound and focused on development tasks, it possesses an indirect prompt injection surface by processing untrusted source code and performing file system operations.

  • Socket16d

    No alerts

  • Snyk16d

    Risk: LOW · No issues

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at 8fc58af. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 3 weeks ago.

Activeupdated 7 months ago
metadata
{
  "author": "JetBrains",
  "version": "1.0.0"
}
  • kotlin
  • java
  • migration
  • spring
  • hibernate
  • jackson
  • junit
  • rxjava
  • retrofit
  • mockito
  • conversion

README badge

README badge for kotlin/kotlin-agent-skills/kotlin-tooling-java-to-kotlin

Converts Java source files to idiomatic Kotlin using a structured 4-step methodology with framework-aware handling for Spring, Lombok, Hibernate, Jackson, Micronaut, Quarkus, Dagger/Hilt, RxJava, JUnit, Guice, Retrofit, and Mockito. Preserves git history through two-phase renames and supports batch conversion with dependency ordering.

Generated from the current SKILL.md.

What frameworks does this skill handle?
Spring, Lombok, Hibernate, Jackson, Micronaut, Quarkus, Dagger/Hilt, RxJava, JUnit, Guice, Retrofit, and Mockito. The skill detects which frameworks are in use by scanning import statements and loads only the relevant framework guides.
Does this skill preserve git blame history?
Yes. It uses a two-phase approach: first rename the file with `git mv`, then replace the content in a separate commit so the rename is tracked separately from the conversion changes.
Can this skill convert multiple Java files at once?
Yes. For batch conversions, it sorts files by dependency order (leaf files first), converts one at a time through the full workflow, and updates cross-references as needed.
What happens if conversion fails the verification step?
The skill reverts to the previous conversion step and retries. It checks five invariants at each step and verifies output by compilation, tests, and annotation site targets.
Does this handle Java interop edge cases like platform types and checked exceptions?
Yes. The skill documents and handles Kotlin keyword conflicts, SAM conversion ambiguity, platform types, @JvmStatic/@JvmField/@JvmOverloads, checked exceptions, and wildcard generics in a separate known-issues reference.

Generated from the current SKILL.md. These answers refresh after source changes.