# Calling Java from Kotlin Kotlin is designed with Java interoperability in mind. Existing Java code can be called from Kotlin in a natural way, and Kotlin code can be used from Java as well. You can use most Java code without additional configuration: ```KOTLIN import java.util.* fun demo(source: List) { val list = ArrayList() // 'for'-loops work for Java collections: for (item in source) { list.add(item) } // Operator conventions work as well: for (i in 0..() // Non-null (constructor result) list.add("Item") val size = list.size // Non-null (primitive int) val item = list[0] // Platform type inferred (ordinary Java object) ``` When you call methods on variables of platform types, Kotlin does not issue nullability errors at compile time, but the call may fail at runtime, because of a null-pointer exception or an assertion that Kotlin generates to prevent nulls from propagating: ```KOTLIN item.substring(1) // Allowed, throws an exception if item == null ``` You can assign a value of a platform type to a variable of both nullable and non-nullable Kotlin types. However, if you assign such a value to a variable of a non-nullable type and the value is actually `null` at runtime, Kotlin throws a `NullPointerException`. To avoid this, add explicit nullability to your Kotlin code: ```KOTLIN val nullable: String? = item // Allowed, always works val notNull: String = item // Allowed, may fail at runtime ``` If you choose a non-nullable type, the compiler will emit an assertion upon assignment. This prevents Kotlin's non-nullable variables from holding nulls. Assertions are also emitted when you pass platform values to Kotlin functions expecting non-null values and in other cases. Overall, the compiler does its best to prevent nulls from propagating far through the program, although sometimes this is impossible to eliminate entirely, because of generics. ### Notation for platform types As mentioned in the previous section, platform types can't be mentioned explicitly in the program, so there's no syntax for them in the language. Nevertheless, the compiler and IDE need to display them sometimes (for example, in error messages or parameter info), so there is a mnemonic notation for them: * `T!` means "`T` or `T?`" * `(Mutable)Collection!` means "Java collection of `T` may be mutable or not, may be nullable or not" * `Array<(out) T>!` means "Java array of `T` (or a subtype of `T`), nullable or not" When you see this notation in an error message or IDE tooltip, add an explicit type annotation to your Kotlin variable to restore null-safety checks or eliminate platform types at the source using nullability annotations. ### Nullability annotations Java types that have nullability annotations are represented not as platform types, but as actual nullable or non-nullable Kotlin types. The compiler supports several flavors of nullability annotations, including: * [JetBrains](https://www.jetbrains.com/idea/help/nullable-and-notnull-annotations.html) (`@Nullable` and `@NotNull` from the `org.jetbrains.annotations` package) * [JSpecify](#jspecify-support) (`org.jspecify.annotations`) * Android (`com.android.annotations`, `android.support.annotation`, `androidx.annotation`, `android.annotation`) * [JSR-305](#jsr-305-support) (`javax.annotation`) * FindBugs (`edu.umd.cs.findbugs.annotations`) * Eclipse (`org.eclipse.jdt.annotation`) * [Lombok](lombok.html) (`lombok.NonNull`) * RxJava 3 (`io.reactivex.rxjava3.annotations`) * [Vert.x](https://vertx.io/) (`io.vertx.codegen.annotations`) You can instruct the compiler to report nullability mismatches for specific nullability annotations with the following compiler option: ```BASH -Xnullability-annotations=@: ``` Specify the package name for the fully qualified nullability annotations and one of these report levels: * `ignore` to ignore nullability mismatches * `warn` to report warnings * `strict` to report errors. Note: [JSpecify](#jspecify-support) is the only supported flavor that uses `strict` report level by default. Use it to report errors on nullability annotations without additional configuration. See the full list of supported nullability annotations in the [Kotlin compiler source code](https://github.com/JetBrains/kotlin/blob/master/core/compiler.common.jvm/src/org/jetbrains/kotlin/load/java/JvmAnnotationNames.kt). ### Mutability annotations You can annotate a Java declaration with a mutability annotation to specify whether a returned collection is read-only or mutable in Kotlin. If you assign the value to a collection type with different mutability, the compiler reports a type mismatch. The diagnostic severity depends on the specific mutability annotation. The compiler supports several mutability annotations, including: * `kotlin.annotations.jvm.ReadOnly` * `kotlin.annotations.jvm.Mutable` * `org.jetbrains.annotations.Unmodifiable` * `org.jetbrains.annotations.UnmodifiableView` See the full list of supported mutability annotations in the [Kotlin compiler source code](https://github.com/JetBrains/kotlin/blob/master/core/compiler.common.jvm/src/org/jetbrains/kotlin/load/java/JvmAnnotationNames.kt). ### Annotating type arguments and type parameters You can annotate the type arguments and type parameters of generic types to provide nullability information for them as well. Note: All examples in the section use JetBrains nullability annotations from the `org.jetbrains.annotations` package. #### Type arguments Consider these annotations on a Java declaration: ```JAVA @NotNull Set<@NotNull String> toSet(@NotNull Collection<@NotNull String> elements) { ... } ``` They result in the following signature in Kotlin: ```KOTLIN fun toSet(elements: (Mutable)Collection) : (Mutable)Set { ... } ``` When the `@NotNull` annotation is missing from a type argument, you get a platform type instead: ```KOTLIN fun toSet(elements: (Mutable)Collection) : (Mutable)Set { ... } ``` Kotlin also takes into account nullability annotations on type arguments of base classes and interfaces. For example, there are two Java classes with the signatures provided below: ```JAVA public class Base {} ``` ```JAVA public class Derived extends Base<@Nullable String> {} ``` In the Kotlin code, passing the instance of `Derived` where the `Base` is assumed produces the warning. ```KOTLIN fun takeBaseOfNotNullStrings(x: Base) {} fun main() { takeBaseOfNotNullStrings(Derived()) // Warning: nullability mismatch } ``` The upper bound of `Derived` is set to `Base`, which is different from `Base`. Learn more about [Java generics in Kotlin](#java-generics-in-kotlin). #### Type parameters By default, the nullability of plain type parameters in both Kotlin and Java is undefined. In Java, you can specify it using nullability annotations. Let's annotate the type parameter of the `Base` class: ```JAVA public class Base<@NotNull T> {} ``` When inheriting from `Base`, Kotlin expects a non-nullable type argument or type parameter. Thus, the following Kotlin code produces a warning: ```KOTLIN class Derived : Base {} // Warning: K has undefined nullability ``` You can fix it by specifying the upper bound `K : Any`. Kotlin also supports nullability annotations on the bounds of Java type parameters. Let's add bounds to `Base`: ```JAVA public class BaseWithBound {} ``` Kotlin translates this just as follows: ```KOTLIN class BaseWithBound {} ``` So passing nullable type as a type argument or type parameter produces a warning. Annotating type arguments and type parameters works with the Java 8 target or higher. The feature requires that the nullability annotations support the `TYPE_USE` target (`org.jetbrains.annotations` supports this in version 15 and above). Note: If a nullability annotation supports other targets that are applicable to a type in addition to the `TYPE_USE` target, `TYPE_USE` takes priority. For example, if `@Nullable` has both `TYPE_USE` and `METHOD` targets, the Java method signature `@Nullable String[] f()` becomes `fun f(): Array!` in Kotlin. ### JSpecify support Kotlin supports the [JSpecify](https://jspecify.dev/) nullability annotations, which provide a unified set of annotations for Java nullability. JSpecify allows you to provide detailed nullability information for Java declarations, helping Kotlin maintain null-safety when working with Java code. Kotlin supports the following annotations in the `org.jspecify.annotations` package: * `@Nullable` marks a type as nullable. * `@NonNull` marks a type as non-nullable. * `@NullMarked` marks all types within a scope, for example a class or package, as non-nullable by default unless annotated otherwise. This annotation doesn't apply to local variables and [type variables (generics)](https://jspecify.dev/docs/user-guide/#using-type-variables-in-generic-types). Type variables remain "null-agnostic" until a specific nullable or non-nullable type is provided. * `@NullUnmarked` reverses the effect of `@NullMarked`, making all types within the scope as [platform types](#null-safety-and-platform-types). Consider the following Java class with JSpecify annotations: ```JAVA // Java import org.jspecify.annotations.*; @NullMarked public class InventoryService { public String notNull() { return ""; } public @Nullable String nullable() { return null; } } ``` In Kotlin, these are treated as regular nullable and non-nullable types rather than [platform types](#null-safety-and-platform-types): ```KOTLIN // Kotlin fun test(inventory: InventoryService) { inventory.notNull().length // OK inventory.nullable().length // Error: only safe (?.) or non-null asserted (!!) calls are allowed } ``` By default, the Kotlin compiler reports nullability mismatches for JSpecify annotations as errors. You can customize the severity of JSpecify nullability diagnostics using the following compiler option: ```BASH -Xjspecify-annotations= ``` Available report levels are: | Level |Description | ---------------------- | `strict` |Reports errors for nullability mismatches (default). | | `warn` |Reports warnings. | | `ignore` |Ignores nullability mismatches. | Tip: For more information on JSpecify annotations, see the [JSpecify user guide](https://jspecify.dev/docs/user-guide). ### JSR-305 support The [@Nonnull](https://www.javadoc.io/doc/com.google.code.findbugs/jsr305/latest/javax/annotation/Nonnull.html) annotation defined in [JSR-305](https://jcp.org/en/jsr/detail?id=305) is supported for denoting nullability of Java types. If the `@Nonnull(when = ...)` value is `When.ALWAYS`, the annotated type is treated as non-nullable; `When.MAYBE` and `When.NEVER` denote a nullable type; and `When.UNKNOWN` forces the type to be [platform one](#null-safety-and-platform-types). A library can be compiled against the JSR-305 annotations, but there's no need to make the artifact with annotations (for example, `jsr305.jar`) a compile dependency for the library consumers. The Kotlin compiler can read the JSR-305 annotations from a library without the annotations present on the classpath. [Custom nullability qualifiers (KEEP-79)](https://github.com/Kotlin/KEEP/blob/master/proposals/jsr-305-custom-nullability-qualifiers.md) are also supported (see below). #### Type qualifier nicknames If an annotation type is annotated with both [@TypeQualifierNickname](https://www.javadoc.io/doc/com.google.code.findbugs/jsr305/latest/javax/annotation/meta/TypeQualifierNickname.html) and JSR-305 `@Nonnull` (or its another nickname, such as `@CheckForNull`), then the annotation type is itself used for retrieving precise nullability and has the same meaning as that nullability annotation: ```JAVA @TypeQualifierNickname @Nonnull(when = When.ALWAYS) @Retention(RetentionPolicy.RUNTIME) public @interface MyNonnull { } @TypeQualifierNickname @CheckForNull // A nickname for another type qualifier nickname @Retention(RetentionPolicy.RUNTIME) public @interface MyNullable { } interface A { @MyNullable String foo(@MyNonnull String x); // In Kotlin (strict mode): `fun foo(x: String): String?` String bar(List<@MyNonnull String> x); // In Kotlin (strict mode): `fun bar(x: List!): String!` } ``` #### Type qualifier defaults [@TypeQualifierDefault](https://www.javadoc.io/doc/com.google.code.findbugs/jsr305/latest/javax/annotation/meta/TypeQualifierDefault.html) allows introducing annotations that, when being applied, define the default nullability within the scope of the annotated element. Such annotation type should itself be annotated with both `@Nonnull` (or its nickname) and `@TypeQualifierDefault(...)` with one or more `ElementType` values: * `ElementType.METHOD` for return types of methods * `ElementType.PARAMETER` for value parameters * `ElementType.FIELD` for fields * `ElementType.TYPE_USE` for any type including type arguments, upper bounds of type parameters and wildcard types The default nullability is used when a type itself is not annotated by a nullability annotation, and the default is determined by the innermost enclosing element annotated with a type qualifier default annotation with the `ElementType` matching the type usage. ```JAVA @Nonnull @TypeQualifierDefault({ElementType.METHOD, ElementType.PARAMETER}) public @interface NonNullApi { } @Nonnull(when = When.MAYBE) @TypeQualifierDefault({ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE_USE}) public @interface NullableApi { } @NullableApi interface A { String foo(String x); // In Kotlin: fun foo(x: String?): String? @NonNullApi // Overriding default from the interface String bar(String x, @Nullable String y); // In Kotlin: fun bar(x: String, y: String?): String // The List type argument is seen as nullable because of `@NullableApi` // having the `TYPE_USE` element type: String baz(List x); // In Kotlin: fun baz(List?): String? // The type of `x` parameter remains platform because there's an explicit // UNKNOWN-marked nullability annotation: String qux(@Nonnull(when = When.UNKNOWN) String x); // In Kotlin: fun qux(x: String!): String? } ``` Note: The types in this example only take place with the strict mode enabled; otherwise, the platform types remain. See the [@UnderMigration annotation](#undermigration-annotation) and [Compiler configuration](#compiler-configuration) sections. Package-level default nullability is also supported: ```JAVA // FILE: test/package-info.java @NonNullApi // Declaring all types in package 'test' as non-nullable by default package test; ``` #### @UnderMigration annotation The `@UnderMigration` annotation (provided in a separate artifact `kotlin-annotations-jvm`) can be used by library maintainers to define the migration status for the nullability type qualifiers. The status value in `@UnderMigration(status = ...)` specifies how the compiler treats inappropriate usages of the annotated types in Kotlin (e.g. using a `@MyNullable`-annotated type value as non-null): * `MigrationStatus.STRICT` makes annotation work as any plain nullability annotation, i.e. report errors for the inappropriate usages and affect the types in the annotated declarations as they are seen in Kotlin * `MigrationStatus.WARN`: the inappropriate usages are reported as compilation warnings instead of errors, but the types in the annotated declarations remain platform * `MigrationStatus.IGNORE` makes the compiler ignore the nullability annotation completely A library maintainer can add `@UnderMigration` status to both type qualifier nicknames and type qualifier defaults: ```JAVA @Nonnull(when = When.ALWAYS) @TypeQualifierDefault({ElementType.METHOD, ElementType.PARAMETER}) @UnderMigration(status = MigrationStatus.WARN) public @interface NonNullApi { } // The types in the class are non-nullable, but only warnings are reported // because `@NonNullApi` is annotated `@UnderMigration(status = MigrationStatus.WARN)` @NonNullApi public class Test {} ``` Note: The migration status of a nullability annotation is not inherited by its type qualifier nicknames but is applied to its usages in default type qualifiers. If a default type qualifier uses a type qualifier nickname and they are both `@UnderMigration`, the status from the default type qualifier is used. #### Compiler configuration The JSR-305 checks can be configured by adding the `-Xjsr305` compiler option with the following values (and their combination): * `-Xjsr305={strict|warn|ignore}` to set up the behavior for non-`@UnderMigration` annotations. Custom nullability qualifiers, especially `@TypeQualifierDefault`, are already spread among many well-known libraries, and users may need to migrate smoothly when updating to the Kotlin version containing JSR-305 support. This option only affects non-`@UnderMigration` annotations. * `-Xjsr305=under-migration:{strict|warn|ignore}` to override the behavior for the `@UnderMigration` annotations. Users may have different view on the migration status for the libraries: they may want to have errors while the official migration status is `WARN`, or vice versa, they may wish to postpone errors reporting for some until they complete their migration. * `-Xjsr305=@:{strict|warn|ignore}` to override the behavior for a single annotation, where `` is the fully qualified class name of the annotation. May appear several times for different annotations. This is useful for managing the migration state for a particular library. The `strict`, `warn` and `ignore` values have the same meaning as those of `MigrationStatus`, and only the `strict` mode affects the types in the annotated declarations as they are seen in Kotlin. Note: The built-in JSR-305 annotations [@Nonnull](https://www.javadoc.io/doc/com.google.code.findbugs/jsr305/latest/javax/annotation/Nonnull.html), [@Nullable](https://www.javadoc.io/doc/com.google.code.findbugs/jsr305/3.0.1/javax/annotation/Nullable.html), and [@CheckForNull](https://www.javadoc.io/doc/com.google.code.findbugs/jsr305/latest/javax/annotation/CheckForNull.html) are always enabled and affect the types of the annotated declarations in Kotlin, regardless of compiler configuration with the `-Xjsr305` option. For example, adding `-Xjsr305=ignore -Xjsr305=under-migration:ignore -Xjsr305=@org.library.MyNullable:warn` to the compiler arguments makes the compiler generate warnings for inappropriate usages of types annotated by `@org.library.MyNullable` and ignore all other JSR-305 annotations. The default behavior is the same to `-Xjsr305=warn`. The `strict` value should be considered experimental (more checks may be added to it in the future). ## Mapped types Kotlin treats some Java types specifically. Such types are not loaded from Java "as is", but are mapped to corresponding Kotlin types. The mapping only matters at compile time, the runtime representation remains unchanged. Java's primitive types are mapped to corresponding Kotlin types (keeping [platform types](#null-safety-and-platform-types) in mind): | Java type |Kotlin type | -------------------------- | `byte` |`kotlin.Byte` | | `short` |`kotlin.Short` | | `int` |`kotlin.Int` | | `long` |`kotlin.Long` | | `char` |`kotlin.Char` | | `float` |`kotlin.Float` | | `double` |`kotlin.Double` | | `boolean` |`kotlin.Boolean` | Some non-primitive built-in classes are also mapped: | Java type |Kotlin type | -------------------------- | `java.lang.Object` |`kotlin.Any!` | | `java.lang.Cloneable` |`kotlin.Cloneable!` | | `java.lang.Comparable` |`kotlin.Comparable!` | | `java.lang.Enum` |`kotlin.Enum!` | | `java.lang.annotation.Annotation` |`kotlin.Annotation!` | | `java.lang.CharSequence` |`kotlin.CharSequence!` | | `java.lang.String` |`kotlin.String!` | | `java.lang.Number` |`kotlin.Number!` | | `java.lang.Throwable` |`kotlin.Throwable!` | Java's boxed primitive types are mapped to nullable Kotlin types: | Java type |Kotlin type | -------------------------- | `java.lang.Byte` |`kotlin.Byte?` | | `java.lang.Short` |`kotlin.Short?` | | `java.lang.Integer` |`kotlin.Int?` | | `java.lang.Long` |`kotlin.Long?` | | `java.lang.Character` |`kotlin.Char?` | | `java.lang.Float` |`kotlin.Float?` | | `java.lang.Double` |`kotlin.Double?` | | `java.lang.Boolean` |`kotlin.Boolean?` | Note that a boxed primitive type used as a type parameter is mapped to a platform type: for example, `List` becomes a `List` in Kotlin. Collection types may be read-only or mutable in Kotlin, so Java's collections are mapped as follows (all Kotlin types in this table reside in the package `kotlin.collections`): | Java type |Kotlin read-only type |Kotlin mutable type |Loaded platform type | ------------------------------------------------------------------------------- | `Iterator` |`Iterator` |`MutableIterator` |`(Mutable)Iterator!` | | `Iterable` |`Iterable` |`MutableIterable` |`(Mutable)Iterable!` | | `Collection` |`Collection` |`MutableCollection` |`(Mutable)Collection!` | | `Set` |`Set` |`MutableSet` |`(Mutable)Set!` | | `List` |`List` |`MutableList` |`(Mutable)List!` | | `ListIterator` |`ListIterator` |`MutableListIterator` |`(Mutable)ListIterator!` | | `Map` |`Map` |`MutableMap` |`(Mutable)Map!` | | `Map.Entry` |`Map.Entry` |`MutableMap.MutableEntry` |`(Mutable)Map.(Mutable)Entry!` | Java's arrays are mapped as mentioned [below](#java-arrays): | Java type |Kotlin type | -------------------------- | `int[]` |`kotlin.IntArray!` | | `String[]` |`kotlin.Array<(out) String!>!` | Note: The static members of these Java types aren't directly accessible on the [companion objects](object-declarations.html#companion-objects) of the Kotlin types. To call them, [use the fully qualified names of the Java types](#accessing-static-members), for example, `java.lang.Integer.toHexString(255)`. ## Java generics in Kotlin Kotlin's generics are a little different from Java's (see [Generics](generics.html)). When importing Java types to Kotlin, the following conversions are done: * Java's wildcards are converted into type projections: * `Foo` becomes `Foo!` * `Foo` becomes `Foo!` * Java's raw types are converted into star projections: * `List` becomes `List<*>!` that is `List!` Like Java's, Kotlin's generics are not retained at runtime: objects do not carry information about actual type arguments passed to their constructors. For example, `ArrayList()` is indistinguishable from `ArrayList()`. This makes it impossible to perform `is`-checks that take generics into account. Kotlin only allows `is`-checks for star-projected generic types: ```KOTLIN if (a is List) // Error: cannot check if it is really a List of Ints // But if (a is List<*>) // OK: no guarantees about the contents of the list ``` ## Java arrays Arrays in Kotlin are invariant, unlike Java. This means that Kotlin won't let you assign an `Array` to an `Array`, which prevents a possible runtime failure. Passing an array of a subclass as an array of superclass to a Kotlin method is also prohibited, but for Java methods this is allowed through [platform types](#null-safety-and-platform-types) of the form `Array<(out) String>!`. Arrays are used with primitive datatypes on the Java platform to avoid the cost of boxing/unboxing operations. As Kotlin hides those implementation details, a workaround is required to interface with Java code. There are specialized classes for every type of primitive array (`IntArray`, `DoubleArray`, `CharArray`, and so on) to handle this case. They are not related to the `Array` class and are compiled down to Java's primitive arrays for maximum performance. Suppose there is a Java method that accepts an int array of indices: ```JAVA public class JavaArrayExample { public void removeIndices(int[] indices) { // Your code here } } ``` To pass an array of primitive values, you can do the following in Kotlin: ```KOTLIN val javaObj = JavaArrayExample() val array = intArrayOf(0, 1, 2, 3) javaObj.removeIndices(array) // Passes int[] to method ``` When compiling to the JVM bytecode, the compiler optimizes access to arrays so that there's no overhead introduced: ```KOTLIN val array = arrayOf(1, 2, 3, 4) array[1] = array[1] * 2 // No actual calls to get() and set() generated for (x in array) { // No iterator created print(x) } ``` Even when you navigate with an index, it does not introduce any overhead: ```KOTLIN for (i in array.indices) { // No iterator created array[i] += 2 } ``` Finally, `in`-checks have no overhead either: ```KOTLIN if (i in array.indices) { // Same as (i >= 0 && i < array.size) print(array[i]) } ``` ## Java varargs Java classes sometimes use a method declaration for the indices with a variable number of arguments (varargs): ```JAVA public class JavaArrayExample { public void removeIndicesVarArg(int... indices) { // Your code here } } ``` In that case, you need to use the spread operator `*` to pass the `IntArray`: ```KOTLIN val javaObj = JavaArrayExample() val array = intArrayOf(0, 1, 2, 3) javaObj.removeIndicesVarArg(*array) ``` ## Operators Since Java has no way of marking methods for which it makes sense to use the operator syntax, Kotlin allows using any Java methods with the right name and signature as operator overloads and other conventions (`invoke()` etc.) Calling Java methods using the infix call syntax is not allowed. For example, you can use a Java class that declares `get(int)` and `set(int, T)` methods with the indexed access operator in Kotlin: ```JAVA public class IntContainer { private final int[] values = new int[10]; public int get(int index) { return values[index]; } public void set(int index, int value) { values[index] = value; } } ``` ```KOTLIN fun main() { val container = IntContainer() container[0] = 42 // Calls set(0, 42) println(container[0]) // Calls get(0) } ``` ## Checked exceptions In Kotlin, all [exceptions are unchecked](exceptions.html), meaning that the compiler does not force you to catch any of them. So, when you call a Java method that declares a checked exception, Kotlin does not force you to do anything: ```KOTLIN fun render(list: List<*>, to: Appendable) { for (item in list) { to.append(item.toString()) // In Java, you'd need to catch IOException thrown from Appendable.append() } } ``` ## Object methods When Java types are imported into Kotlin, all the references of the type `java.lang.Object` are turned into `Any`. Since `Any` is not platform-specific, it only declares `toString()`, `hashCode()` and `equals()` as its members, so to make other members of `java.lang.Object` available, Kotlin uses [extension functions](extensions.html). ### `wait()` and `notify()` Methods `wait()` and `notify()` are not available on references of type `Any`. Their usage is generally discouraged in favor of `java.util.concurrent`. If you have to call these methods, access them through Java objects and suppress the `PLATFORM_CLASS_MAPPED_TO_KOTLIN` warning: ```KOTLIN import java.util.LinkedList class SimpleBlockingQueue(private val capacity: Int) { private val queue = LinkedList() // Uses a java.lang.Object instance to access wait() and notify() // In Kotlin, the standard 'Any' type doesn't expose these methods @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") private val lock = Object() fun put(item: T) { synchronized(lock) { while (queue.size >= capacity) { lock.wait() } queue.add(item) println("Produced: $item") lock.notifyAll() } } fun take(): T { synchronized(lock) { while (queue.isEmpty()) { lock.wait() } val item = queue.removeFirst() println("Consumed: $item") lock.notifyAll() return item } } } ``` Or explicitly cast to `java.lang.Object` and suppress the `PLATFORM_CLASS_MAPPED_TO_KOTLIN` warning: ```KOTLIN @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") (instance as java.lang.Object).wait() ``` ### `getClass()` To retrieve the Java class of an object, use the `java` extension property on a [class reference](reflection.html#obtain-a-runtime-class): ```KOTLIN val instanceClass = instance::class.java ``` The code above uses a [bound class reference](lambdas.html#bound-and-unbound-references). You can also use the `javaClass` extension property: ```KOTLIN val instanceClass = instance.javaClass ``` ### `clone()` To override `clone()`, your class needs to extend `kotlin.Cloneable`: ```KOTLIN class Example : Cloneable { override fun clone(): Any { ... } } ``` Don't forget about [Effective Java, 3rd Edition](https://www.oracle.com/technetwork/java/effectivejava-136174.html), Item 13: Override clone judiciously. ### `finalize()` To override `finalize()`, declare it without using the `override` keyword: ```KOTLIN class C { protected fun finalize() { // Finalization logic } } ``` According to Java's rules, `finalize()` must not be `private`. Note: The `finalize()` method is deprecated in modern Java versions. Consider alternatives such as [java.lang.ref.Cleaner](https://docs.oracle.com/javase/9/docs/api/java/lang/ref/Cleaner.html) or [try-with-resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) instead. ## Inheritance from Java classes At most one Java class (and as many Java interfaces as you like) can be a supertype for a class in Kotlin. ## Accessing static members Static members of Java classes form "companion objects" for these classes. You can't pass such a "companion object" around as a value but can access the members explicitly, for example: ```KOTLIN if (Character.isLetter(a)) { ... } ``` To call a static method of an imported Java class, use the class name directly, just like in Java. Consider the following Java class: ```JAVA package org.example; public class MathUtils { public static int triple(int value) { return value * 3; } } ``` Import the class and call its static method through the class name: ```KOTLIN import org.example.MathUtils fun main() { println(MathUtils.triple(5)) // Calls the static triple() method } ``` To access static members of a Java type that is [mapped](#mapped-types) to a Kotlin type, use the fully qualified name of the Java type: `java.lang.Integer.bitCount(5)`. ## Java reflection Java reflection works on Kotlin classes and vice versa. As mentioned above, you can use `instance::class.java`, `ClassName::class.java` or `instance.javaClass` to enter Java reflection through `java.lang.Class`. Don't use `ClassName.javaClass` for this purpose because it refers to `ClassName`'s [companion object](object-declarations.html#companion-objects) class, which is the same as `ClassName.Companion::class.java` and not `ClassName::class.java`. For each primitive type, there are two different Java classes, and Kotlin provides ways to get both. For example, `Int::class.java` will return the class instance representing the primitive type itself, corresponding to `Integer.TYPE` in Java. To get the class of the corresponding wrapper type, use `Int::class.javaObjectType`, which is equivalent of Java's `Integer.class`. Other supported cases include acquiring a Java getter/setter method or a backing field for a Kotlin property, a `KProperty` for a Java field, a Java method or constructor for a `KFunction`, and vice versa. ## SAM conversions Kotlin supports SAM conversions for both Java and [Kotlin interfaces](fun-interfaces.html). This support for Java means that Kotlin function literals can be automatically converted into implementations of Java interfaces with a single non-default method, as long as the parameter types of the interface method match the parameter types of the Kotlin function. You can use this for creating instances of SAM interfaces: ```KOTLIN val runnable = Runnable { println("This runs in a runnable") } ``` And in method calls: ```KOTLIN val executor = Executors.newSingleThreadExecutor() // Java signature: void execute(Runnable command) executor.execute { println("This runs in a thread pool") } ``` If the Java class has multiple methods taking functional interfaces, you can choose the one you need to call by using an adapter function that converts a lambda to a specific SAM type. Those adapter functions are also generated by the compiler when needed: ```KOTLIN executor.execute(Runnable { println("This runs in a thread pool") }) ``` Note: SAM conversions only work for interfaces. They don't apply to abstract classes, even if those classes have only one abstract method. ## Using JNI with Kotlin To declare a function that is implemented in native (C or C++) code, you need to mark it with the `external` modifier: ```KOTLIN external fun calculateSum(x: Int): Double ``` The rest of the procedure works in exactly the same way as in Java. You can also mark property getters and setters as `external`: ```KOTLIN var myProperty: String external get external set ``` Behind the scenes, this will create two functions `getMyProperty` and `setMyProperty`, both marked as `external`. ## Using Lombok-generated declarations in Kotlin You can use Java's Lombok-generated declarations in Kotlin code. If you need to generate and use these declarations in the same mixed Java/Kotlin module, you can learn how to do this on the [Lombok compiler plugin's page](lombok.html). If you call such declarations from another module, then you don't need to use this plugin to compile that module.