Kotlin was first designed for easy interoperation with the Java platform: it sees Java classes as Kotlin classes, and Java sees Kotlin classes as Java classes.
js() function. For example:
Because the parameter of
Note that invoking
js() returns a result of type
dynamic, which provides no type safety at the compile time.
external declarations can't have a body. For example:
Note that the
external modifier is inherited by nested declarations. This is why in the example
Node class, there is no
external modifier before member functions and properties.
external modifier is only allowed on package-level declarations. You can't declare an
external member of a non-
Declare (static) members of a class
There is no such syntax in Kotlin. However, in Kotlin we have
companion objects. Kotlin treats companion objects of
external classes in a special way: instead of expecting an object, it assumes members of companion objects to be members of the class itself.
MyClass from the example above can be described as follows:
Declare optional parameters
With this external declaration, you can call
external open class and extend it by a non-
external class. For example:
There are some limitations:
When a function of an external base class is overloaded by signature, you can't override it in a derived class.
You can't override a function with default arguments.
Non-external classes can't be extended by external classes.
bar, you would just pass in an object that actually has these methods.
You can use interfaces to express this concept in statically typed Kotlin:
A typical use case for external interfaces is to describe settings objects. For example:
External interfaces have some restrictions:
They can't be used on the right-hand side of
They can't be passed as reified type arguments.
They can't be used in class literal expressions (such as
ascasts to external interfaces always succeed. Casting to external interfaces produces the "Unchecked cast to external interface" compile time warning. The warning can be suppressed with the
IntelliJ IDEA can also automatically generate the
@Suppressannotation. Open the intentions menu via the light bulb icon or Alt-Enter, and click the small arrow next to the "Unchecked cast to external interface" inspection. Here, you can select the suppression scope, and your IDE will add the annotation to your file accordingly.
In addition to the "unsafe" cast operator
as, which throws a
ClassCastException in case a cast is not possible, Kotlin/JS also provides
unsafeCast<T>(). When using
unsafeCast, no type checking is done at all during runtime. For example, consider the following two methods:
They will be compiled accordingly: