search
HomeJavajavaTutorialSummary of calling js methods in Kotlin

Summary of calling js methods in Kotlin

Jun 17, 2017 am 11:57 AM
javascriptkotlinSummarizemethodtransfer

This article mainly introduces the relevant information about the detailed explanation of the method instance of calling JavaScript in the Kotlin language. Friends in need can refer to the detailed explanation of the instance of calling the JavaScript method in the Kotlin language.

Kotlin has been designed to easily interoperate with the Java platform. It treats Java classes as Kotlin classes, and Java treats Kotlin classes as Java classes. However, JavaScript is a dynamically typed language, which means it does not check types at compile time. You can freely communicate with JavaScript in Kotlin through dynamic typing, but if you want the full power of the Kotlin type system, you can create Kotlin header files for your JavaScript libraries.

Inline JavaScript

You can embed some JavaScript code into Kotlin code using the js("...") function. For example:

fun jsTypeOf(o: Any): String {
 return js("typeof o")
}

js parameters must be
string

constants. Therefore, the following code is incorrect:

fun jsTypeOf(o: Any): String {
 return js(getTypeof() + " o") // 此处报错
}
fun getTypeof() = "typeof"


external modifier

tells Kotlin that a certain declaration is made in pure JavaScript written, you should mark it with the external modifier. When the compiler sees such a declaration, it assumes that the implementation of the corresponding class, function, or property was provided by the developer, and therefore does not attempt to generate any JavaScript code from the declaration. This means you should omit the body of the external declaration content. For example:

external fun alert(message: Any?): Unit

external class Node {
 val firstChild: Node

 fun append(child: Node): Node

 fun removeChild(child: Node): Node

 // 等等
}
external val window: Window

Please note that nested declarations inherit the external modifier, that is, in the Node class, we do not place external before member functions and properties.

The external modifier is only allowed in package-level declarations. You cannot declare an external member of a non-external class.


Declaring (

static

) members of a classIn JavaScript, you can define members on the prototype or on the class itself. That is:

function MyClass() {
}
MyClass.sharedMember = function() { /* 实现 */ };
MyClass.prototype.ownMember = function() { /* 实现 */ };

There is no such syntax in Kotlin. However, in Kotlin we have companion objects. Kotlin treats companion objects of the external class in a special way: instead of expecting an object, it assumes that the members of the companion object are members of the class itself. To describe MyClass from the above example, you could write:

external class MyClass {
 companion object {
  fun sharedMember()
 }

 fun ownMember()
}


Declare optional parameters

An external function can There are optional parameters. How the JavaScript implementation actually calculates the default values ​​of these parameters is unknown to Kotlin, so it is not possible to declare these parameters using the usual syntax in Kotlin. You should use the following syntax:

external fun myFunWithOptionalArgs(x: Int,
 y: String = definedExternally,
 z: Long = definedExternally)

This means you can call myFunWithOptionalArgs with one required argument and two optional arguments (their default values ​​are figured out by some JavaScript code ).

Extending JavaScript classes

You can easily extend JavaScript classes because they are Kotlin classes. Just define an external class and extend it with non-external classes. For example:

external open class HTMLElement : Element() {
 /* 成员 */
}

class CustomElement : HTMLElement() {
 fun foo() {
  alert("bar")
 }
}

There are some restrictions:

When a function of an external base class is signed

overloaded

, it cannot be derived class override it.

Cannot override a function that uses default parameters.

Please note that you cannot extend a non-external class with an external class.

external interface

JavaScript has no concept of interface. When a function expects its arguments to support foo and bar methods, just pass the object that actually has those methods. For statically typed Kotlin, you can express this using interfaces, for example:

external interface HasFooAndBar {
 fun foo()

 fun bar()
}

external fun myFunction(p: HasFooAndBar)

Another use case for external interfaces is to describe settings objects. For example:

external interface JQueryAjaxSettings {
 var async: Boolean

 var cache: Boolean

 var complete: (JQueryXHR, String) -> Unit

 // 等等
}

fun JQueryAjaxSettings(): JQueryAjaxSettings = js("{}")

external class JQuery {
 companion object {
  fun get(settings: JQueryAjaxSettings): JQueryXHR
 }
}

fun sendQuery() {
 JQuery.get(JQueryAjaxSettings().apply {
  complete = { (xhr, data) ->
   window.alert("Request complete")
  }
 })
}


External interfaces have some restrictions:

They cannot be used on the right side of an is check. as conversion to an external interface always succeeds (and produces a warning at compile time).

They cannot be passed as reified type parameters.

They cannot be used in class literal
expressions
(i.e. I
::class).

The above is the detailed content of Summary of calling js methods in Kotlin. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor