Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Java interoperability

Kotlin Java interoperability

From the very beginning of its design, Kotlin has treated "seamless interoperability with Java" as a core goal; both run on the JVM after compilation and can call each other directly.

This chapter covers the rules for calling in both directions, the null-safety risks brought by platform types, and several annotations that make calling from Java friendlier.


Calling Java from Kotlin

Kotlin can use any Java class directly, without extra wrapping.

Kotlin also adds syntactic sugar for Java getters and setters: person.getName() can be written as person.name.

Let's first look at an ordinary Java class.

Example

// File path: Person.java

public

class

Person

{

   

private

String

name

;

         

// Private field

   

private

int

age

;

   

public

Person

(

String

name,

int

age

)

{

       

this

.

name

=

name

;

       

this

.

age

=

age

;

   

}

   

// Java's getter / setter

   

public

String

getName

(

)

{

return

name

;

}

   

public

void

setName

(

String

name

)

{

this

.

name

=

name

;

}

   

public

int

getAge

(

)

{

return

age

;

}

   

public

void

setAge

(

int

age

)

{

this

.

age

=

age

;

}

   

// Static method

   

public

static

String

welcome

(

String

site

)

{

       

return

"Welcome to "

site

;

   

}

}

When calling this class from Kotlin, you can omit the getter and setter syntax.

Example

// File path: Main.kt

fun main

(

)

{

    val person

=

Person

(

"RUNOOB"

,

10

)

   

// You can use property syntax directly when calling a Java getter

    println

(

person.

name

)

             

// Equivalent to person.getName()

    println

(

person.

age

)

             

// Equivalent to person.getAge()

   

// You can also use property assignment directly when calling a Java setter

    person.

age

=

20

                 

// Equivalent to person.setAge(20)

    println

(

"After modification: ${person.age}"

)

   

// Call static methods the Java way

    println

(

Person.

welcome

(

"www.runoob.com"

)

)

}

The example produces the following output:



RUNOOB

10

修改后:20

欢迎来到 www.runoob.com

Java's static members are also called statically in Kotlin, with exactly the same syntax.

Kotlin does not force you to catch Java's checked exceptions; it treats all exceptions as unchecked.


Calling Kotlin from Java

Conversely, when Java calls Kotlin, you need to pay attention to how Kotlin-specific constructs appear on the JVM.

Top-level functions are placed in a class named "FileName + Kt", and companion object members must be accessed through Companion.

Example

// File path: Runoob.kt

class

Runoob

{

    companion object

{

       

// Without @JvmStatic, Java must write Runoob.Companion.currentVersion()

        fun currentVersion

(

)

:

String

=

"Kotlin 2.2"

       

// With @JvmStatic, Java can write Runoob.staticVersion() directly

        @JvmStatic

        fun staticVersion

(

)

:

String

=

"Kotlin 2.2"

       

// const val generates a static constant field

       

const

val SITE

:

String

=

"www.runoob.com"

   

}

}

// Top-level functions generate a RunoobKt class (file name + Kt)

fun topLevelHello

(

)

:

String

=

"Greetings from a top-level function"

The corresponding Java calling code is as follows.

Example

// File path: Main.java

public

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

       

System

.

out

.

println

(

Runoob.

Companion

.

currentVersion

(

)

)

;

// Companion objects go through Companion

       

System

.

out

.

println

(

Runoob.

staticVersion

(

)

)

;

           

// @JvmStatic becomes a static method

       

System

.

out

.

println

(

Runoob.

SITE

)

;

                     

// const val is a static field

       

System

.

out

.

println

(

RunoobKt.

topLevelHello

(

)

)

;

         

// Top-level functions are in RunoobKt

   

}

}

The output is:



Kotlin 2.2

Kotlin 2.2

www.runoob.com

来自顶层函数的问候

Kotlin's object singleton has a static field INSTANCE on the JVM, so Java must write Runoob.INSTANCE.foo().

If you want to change the "FileName + Kt" class name, you can use the file-level annotation @file:JvmName.

Example

// File path: Utils.kt

@file

:

JvmName

(

"RunoobUtils"

)

       

// File annotations must be written before package

package

com.runoob

fun version

(

)

:

String

=

"Kotlin 2.2"

This way Java can write RunoobUtils.version() instead of UtilsKt.version().


Platform Types and Null-Safety Risks

Java's type system has no nullability information; Kotlin calls such a type that "may or may not be null" a platform type, written as String!.

A platform type can be assigned to a non-null type or to a nullable type, and the compiler performs no checks — that's where the risk lies.

Example

// File path: MessageService.java

public

class

MessageService

{

   

// Without @Nullable / @NotNull annotations, the return value is the platform type String!

   

public

String

getMessage

(

)

{

       

return

null

;

             

// May return null at runtime

   

}

}

If Kotlin uses it directly as a non-null type, compilation succeeds but a null pointer is thrown at runtime.

Example

// File path: Main.kt

fun main

(

)

{

    val service

=

MessageService

(

)

   

// Declare it as a nullable type and force yourself to check for null — this is the recommended practice

    val message

:

String

?

=

service.

message

    println

(

"Content: $message"

)

    println

(

"Length: ${message?.length ?: 0}"

)

}

The example produces the following output:



内容:null

长度:0

Note:If you write the above as val message: String = service.message, the compiler reports no error, but when execution reaches message.length it will throw NullPointerException. So when calling Java code without nullability annotations, it's safer to proactively declare the return value as a nullable type.

If the Java side uses JSR-305's @Nullable or @NotNull, or Android's androidx.annotation family of annotations, Kotlin recognizes them and generates genuine nullable types.

Java-side notation Type seen by Kotlin Null-safe
Unannotated String String!(platform type) No checks, highest risk
@Nullable String String? Compiler enforces null checks
@NotNull String String Treated as non-null

Common Interoperability Annotations

Kotlin provides a set of annotations starting with @Jvm to control the generated JVM bytecode and make calling from Java more natural.

Annotation Purpose Applicable locations
@JvmStatic Generate real static members in a companion object or object Functions, properties
@JvmField Expose a property directly as a field, with no getter/setter generated Properties with a backing field
@JvmOverloads Generate multiple overloads for parameters with default values Functions, constructors
@JvmName Change the generated JVM name Functions, accessors, files
@Throws Declare checked exceptions in bytecode Functions, constructors, property accessors

The following example demonstrates several common annotations together.

Example

// File path: Config.kt

import

java.io.IOException

class

Config

{

   

// @JvmField: Java accesses the field config.timeout directly

    @JvmField

    val timeout

:

Int

=

3000

   

// Ordinary val: Java must access it through getPort()

    val port

:

Int

=

8080

}

class

Formatter

{

   

// @JvmOverloads: generate overloads with 1, 2, and 3 parameters for default arguments

    @JvmOverloads

    fun format

(

text

:

String

, prefix

:

String

=

"[RUNOOB] "

, upper

:

Boolean

=

false

)

:

String

{

        val result

=

prefix

text

       

return

if

(

upper

)

result.

uppercase

(

)

else

result

   

}

   

// @Throws: lets Java see a checked exception, so callers must try/catch

    @

Throws

(

IOException

::

class

)

    fun readConfig

(

path

:

String

)

:

String

{

       

if

(

path.

isEmpty

(

)

)

throw

IOException

(

"Path cannot be empty"

)

       

return

"Read succeeded: $path"

   

}

}

// @JvmName: change the generated JVM method name

@JvmName

(

"greetFromKotlin"

)

fun greet

(

name

:

String

)

:

String

=

"Hello, $name"

The calling code on the Java side looks like this.

Example

// File path: Main.java

import

java.io.IOException

;

public

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

throws

IOException

{

        Config config

=

new

Config

(

)

;

       

System

.

out

.

println

(

config.

timeout

)

;

     

// @JvmField: access the field directly

       

System

.

out

.

println

(

config.

getPort

(

)

)

;

   

// Ordinary property: goes through the getter

        Formatter formatter

=

new

Formatter

(

)

;

       

System

.

out

.

println

(

formatter.

format

(

"hello"

)

)

;

                   

// 1 parameter

       

System

.

out

.

println

(

formatter.

format

(

"hello"

,

"kotlin "

)

)

;

         

// 2 parameters

       

System

.

out

.

println

(

formatter.

format

(

"hello"

,

"kotlin "

,

true

)

)

;

   

// 3 parameters

       

System

.

out

.

println

(

formatter.

readConfig

(

"runoob.conf"

)

)

;

       

System

.

out

.

println

(

ConfigKt.

greetFromKotlin

(

"RUNOOB"

)

)

;

           

// The name after @JvmName

   

}

}

The output is:



3000

8080

[RUNOOB] hello

kotlin hello

KOTLIN HELLO

读取成功:runoob.conf

你好,RUNOOB

Tip:@JvmField has conditions for use: the property must have a backing field, must not be private, and must not be open、override or const。


Property-to-getter/setter Mapping Rules

Kotlin properties don't exist directly on the JVM; the compiler generates a private field and accessors for them.

Two-way mapping between Kotlin and Java: properties map to getters and setters, default parameters require JvmOverloads, top-level functions generate FileKt static methods, and companion object members require JvmStatic to be static methods

Remember this mapping table and you can infer what syntax to use on the Java side.

Kotlin declaration Generated JVM member Java access style
val name: String Private field + getName() obj.getName()
var name: String Private field + getName() / setName() obj.setName("x")
val isOpen: Boolean isOpen() obj.isOpen()
var isOpen: Boolean isOpen() / setOpen() obj.setOpen(true)
@JvmField val name: String Public field name obj.name
In a companion object @JvmStatic fun foo() Static methods foo() Runoob.foo()
object Runoob Singleton + static field INSTANCE Runoob.INSTANCE.foo()

When a boolean property starts with is, the getter gets no get prefix and is simply the property name itself.

If you only want to change the accessor names rather than turn the whole property into a field, use @get:JvmName and @set:JvmName.

Example

// File path: Site.kt

class

Site

{

   

// Only the getter name changes; Java uses getSiteUrl()

    @get

:

JvmName

(

"getSiteUrl"

)

    val url

:

String

=

"www.runoob.com"

   

// Boolean property; Java sees isActive()

    val isActive

:

Boolean

=

true

}


Default Arguments and Java Overloads

Java has no concept of default arguments; when a Kotlin function has default values, Java must pass all arguments.

The compiler generates a synthetic method with a $default suffix for default arguments, but calling it directly from Java is awkward.

Example

// File path: Greeter.kt

class

Greeter

{

   

// Without @JvmOverloads: Java can only write greeter.greet("RUNOOB", "Hello, ")

    fun greet

(

name

:

String

, prefix

:

String

=

"Hello, "

)

:

String

=

"$prefix$name"

   

// With @JvmOverloads: Java can pass just name

    @JvmOverloads

    fun greetShort

(

name

:

String

, prefix

:

String

=

"Hello, "

)

:

String

=

"$prefix$name"

}

With the annotation, the Java side can call with different numbers of arguments, just like ordinary overloaded methods.

Example

// File path: Main.java

public

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

        Greeter greeter

=

new

Greeter

(

)

;

       

System

.

out

.

println

(

greeter.

greet

(

"RUNOOB"

,

"Hello, "

)

)

;

       

System

.

out

.

println

(

greeter.

greetShort

(

"RUNOOB"

)

)

;

       

System

.

out

.

println

(

greeter.

greetShort

(

"RUNOOB"

,

"Welcome, "

)

)

;

   

}

}

The output is:



你好,RUNOOB

你好,RUNOOB

欢迎,RUNOOB

Note:@JvmOverloads It generates an overload for every default argument, which significantly increases the method count when there are many parameters. When you have more than three or four parameters, consider switching to the Builder pattern or a configuration object.


SAM Conversion

SAM conversion means using a lambda directly as an implementation of an interface with a single abstract method.

Java's functional interfaces naturally support this syntax in Kotlin, such as Runnable, Comparator, and Callable.

Example

// File path: Task.java

public

interface

Task

{

   

void

run

(

String

name

)

;

       

// Only one abstract method

}

On the Kotlin side you can implement this interface directly with a lambda.

Example

// File path: Main.kt

fun execute

(

task

:

Task

)

{

    task.

run

(

"RUNOOB"

)

}

// Since Kotlin 1.4 you can declare functional interfaces with fun interface

fun

interface

Printer

{

    fun print

(

text

:

String

)

}

fun main

(

)

{

   

// Pass a lambda directly to a Java interface in Kotlin

    execute

{

name

->

println

(

"Executing task: $name"

)

}

   

// Kotlin's own fun interface also supports SAM conversion

    val printer

=

Printer

{

text

->

println

(

text

)

}

    printer.

print

(

"www.runoob.com"

)

}

The example produces the following output:



执行任务:RUNOOB

www.runoob.com

Before Kotlin 1.4, only Java interfaces supported SAM conversion; Kotlin interfaces had to be written as object expressions.

Note the reverse scenario: when Java calls a Kotlin () -> Unit parameter, it sees Function0, which must be implemented explicitly.

Example

// File path: Runner.kt

// When called from Java you can only pass Function0, which is not very friendly

fun runKotlinStyle

(

action

:

(

)

->

Unit

)

{

    action

(

)

}

Example

// File path: Main.java

import

kotlin.Unit

;

import

kotlin.jvm.functions.Function0

;

public

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Java must implement Function0 explicitly and also return Unit.INSTANCE

        RunnerKt.

runKotlinStyle

(

new

Function0

<

Unit

(

)

{

@Override

public

Unit invoke

(

)

{

               

System

.

out

.

println

(

"A call from Java"

)

;

               

return

Unit.

INSTANCE

;

           

}

       

}

)

;

   

}

}

The output is:



来自 Java 的调用

Tip:If an API is mainly meant to be called from Java, declare the parameter type as a Java functional interface (for example Runnable) or Kotlin's fun interface, and the Java side can write lambdas directly, which is much nicer.


Version notes

Most interoperability-related annotations have existed since Kotlin 1.0, with a few features added later.

Feature Starting version Description
@JvmStatic / @JvmField / @JvmOverloads Since Kotlin 1.0 Basic JVM interoperability annotations
@JvmName / @Throws Since Kotlin 1.0 Renaming and checked exception declarations
fun interface and SAM conversion Since Kotlin 1.4 Kotlin interfaces can also be implemented with lambdas
@JvmRecord Since Kotlin 1.5 Generate Java record types
-jvm-default Option Stable since Kotlin 2.2 Control how interface default methods generate JVM default methods

Common questions

The following questions often come up in real projects.

Java can't find a Kotlin function

First check whether it's a top-level function, which lives in the "FileName + Kt" class; if the function has default arguments, Java must pass all of them, or you can add @JvmOverloads to the function.

Why must get be added when Java accesses Kotlin properties

Kotlin's val name generates getName(). To access the field directly, add @JvmField; to change the name, use @get:JvmName.

Why can't companion object members be called directly

A companion object is a static instance named Companion that Java must go through; only after adding @JvmStatic are real static methods generated.

Where did checked exceptions go when Kotlin calls Java

Kotlin has no checked exceptions; checked exceptions thrown by Java are treated in Kotlin like any other exception — you must try/catch yourself, and the compiler doesn't force it.

Can platform types be completely avoided

No. As long as the Java code you call has no nullability annotations, platform types arise. The approach is to explicitly declare return values as nullable wherever possible, or push the Java side to add annotations.