0
# JavaScript Interoperability
1
2
Core JavaScript interoperability functionality for seamless integration between Kotlin and JavaScript code, including dynamic typing, JSON manipulation, Promise support, and regular expressions.
3
4
## Capabilities
5
6
### Inline JavaScript Execution
7
8
Execute JavaScript code directly within Kotlin functions.
9
10
```kotlin { .api }
11
/**
12
* Puts the given piece of JavaScript code right into the calling function.
13
* The compiler replaces call to `js(...)` with the string constant provided as parameter.
14
* @param code the piece of JavaScript code to put to the generated code. Must be compile-time constant.
15
*/
16
external fun js(code: String): dynamic
17
```
18
19
**Usage Examples:**
20
21
```kotlin
22
// Execute JavaScript Math functions
23
val max = js("Math.max(1, 2, 3)")
24
val random = js("Math.random()")
25
26
// Access JavaScript objects
27
val console = js("console")
28
js("console.log('Hello from Kotlin!')")
29
30
// Variable references
31
fun logMessage(message: String) {
32
js("console.log(message)") // Can reference Kotlin parameters
33
}
34
```
35
36
### JavaScript Type Operations
37
38
Type checking and conversion utilities for JavaScript interoperability.
39
40
```kotlin { .api }
41
/**
42
* Function corresponding to JavaScript's `typeof` operator
43
*/
44
external fun jsTypeOf(a: Any?): String
45
46
/**
47
* Placeholder for external function bodies and default parameters
48
*/
49
external val definedExternally: Nothing
50
51
/**
52
* Cast any value to dynamic type
53
*/
54
inline fun Any?.asDynamic(): dynamic
55
56
/**
57
* Unsafe type casting - bypasses Kotlin type system
58
*/
59
inline fun <T> Any?.unsafeCast(): T
60
```
61
62
**Usage Examples:**
63
64
```kotlin
65
val obj: Any = "hello"
66
val type = jsTypeOf(obj) // "string"
67
68
val dynamic = obj.asDynamic()
69
dynamic.length // Access JavaScript properties
70
71
val str: String = obj.unsafeCast<String>() // Force type cast
72
73
val isUndefined = obj === undefined
74
```
75
76
### JSON Support
77
78
Type-safe JSON object creation and manipulation.
79
80
```kotlin { .api }
81
/**
82
* JSON object interface with indexing operations
83
*/
84
external interface Json {
85
operator fun get(key: String): Any?
86
operator fun set(key: String, value: Any?)
87
}
88
89
/**
90
* Create JSON objects from key-value pairs
91
*/
92
fun json(vararg pairs: Pair<String, Any?>): Json
93
94
/**
95
* Add properties from another JSON object
96
*/
97
fun Json.add(other: Json): Json
98
99
/**
100
* JavaScript JSON object with global methods
101
*/
102
external object JSON {
103
fun stringify(value: Any?): String
104
fun stringify(value: Any?, replacer: Array<String>?): String
105
fun stringify(value: Any?, replacer: ((key: String, value: Any?) -> Any?)?): String
106
fun parse(text: String): dynamic
107
fun parse(text: String, reviver: (key: String, value: Any?) -> Any?): dynamic
108
}
109
```
110
111
**Usage Examples:**
112
113
```kotlin
114
// Create JSON objects
115
val person = json(
116
"name" to "John Doe",
117
"age" to 30,
118
"active" to true
119
)
120
121
// Access properties
122
val name = person["name"]
123
person["email"] = "john@example.com"
124
125
// Merge objects
126
val address = json("city" to "New York", "zip" to "10001")
127
val combined = person.add(address)
128
129
// JavaScript JSON methods
130
val jsonString = JSON.stringify(person)
131
val parsed = JSON.parse(jsonString)
132
```
133
134
### Promise Support
135
136
JavaScript Promise wrapper with type-safe chaining and error handling.
137
138
```kotlin { .api }
139
/**
140
* JavaScript Promise wrapper
141
*/
142
external class Promise<out T> {
143
constructor(executor: (resolve: (T) -> Unit, reject: (Throwable) -> Unit) -> Unit)
144
145
fun <R> then(onFulfilled: ((T) -> R)?): Promise<R>
146
fun <R> then(onFulfilled: ((T) -> R)?, onRejected: ((Throwable) -> R)?): Promise<R>
147
fun <R> catch(onRejected: (Throwable) -> R): Promise<R>
148
fun <R> finally(onFinally: () -> Unit): Promise<T>
149
150
companion object {
151
fun <T> resolve(value: T): Promise<T>
152
fun <T> reject(reason: Throwable): Promise<T>
153
fun <T> all(promises: Array<Promise<T>>): Promise<Array<T>>
154
fun <T> race(promises: Array<Promise<T>>): Promise<T>
155
}
156
}
157
```
158
159
**Usage Examples:**
160
161
```kotlin
162
// Create promises
163
val promise = Promise<String> { resolve, reject ->
164
// Async operation
165
resolve("Success!")
166
}
167
168
// Chain operations
169
promise
170
.then { result -> result.uppercase() }
171
.then { upper -> console.log(upper) }
172
.catch { error -> console.error("Error: $error") }
173
174
// Static methods
175
val resolved = Promise.resolve("Immediate value")
176
val rejected = Promise.reject(RuntimeException("Error"))
177
178
// Multiple promises
179
val promises = arrayOf(
180
Promise.resolve(1),
181
Promise.resolve(2),
182
Promise.resolve(3)
183
)
184
Promise.all(promises).then { results ->
185
console.log("All resolved: ${results.joinToString()}")
186
}
187
```
188
189
### Regular Expressions
190
191
JavaScript RegExp wrapper with pattern matching capabilities.
192
193
```kotlin { .api }
194
/**
195
* JavaScript regular expression
196
*/
197
external class RegExp {
198
constructor(pattern: String)
199
constructor(pattern: String, flags: String?)
200
201
val global: Boolean
202
val ignoreCase: Boolean
203
val multiline: Boolean
204
val source: String
205
var lastIndex: Int
206
207
fun test(string: String): Boolean
208
fun exec(string: String): RegExpMatch?
209
}
210
211
/**
212
* Regular expression match result
213
*/
214
external interface RegExpMatch {
215
val index: Int
216
val input: String
217
operator fun get(index: Int): String?
218
val length: Int
219
}
220
221
/**
222
* Reset regex state (clear lastIndex)
223
*/
224
fun RegExp.reset()
225
```
226
227
**Usage Examples:**
228
229
```kotlin
230
// Create regex patterns
231
val emailRegex = RegExp("""[\w._%+-]+@[\w.-]+\.[A-Za-z]{2,}""")
232
val phoneRegex = RegExp("""\d{3}-\d{3}-\d{4}""")
233
234
// Test strings
235
val isEmail = emailRegex.test("user@example.com") // true
236
val isPhone = phoneRegex.test("123-456-7890") // true
237
238
// Extract matches
239
val pattern = RegExp("""(\d{4})-(\d{2})-(\d{2})""")
240
val match = pattern.exec("2023-12-25")
241
if (match != null) {
242
val year = match[1] // "2023"
243
val month = match[2] // "12"
244
val day = match[3] // "25"
245
}
246
247
// Global matching
248
val globalPattern = RegExp("""\w+""", "g")
249
globalPattern.reset() // Reset before reuse
250
```
251
252
### JavaScript Collections Interfaces
253
254
Read-only interfaces for JavaScript native collection types.
255
256
```kotlin { .api }
257
/**
258
* Read-only JavaScript Array interface
259
*/
260
external interface JsReadonlyArray<out E> {
261
val length: Int
262
operator fun get(index: Int): E
263
}
264
265
/**
266
* Read-only JavaScript Set interface
267
*/
268
external interface JsReadonlySet<out E> {
269
val size: Int
270
fun has(value: E): Boolean
271
}
272
273
/**
274
* Read-only JavaScript Map interface
275
*/
276
external interface JsReadonlyMap<K, out V> {
277
val size: Int
278
fun has(key: K): Boolean
279
fun get(key: K): V?
280
}
281
```
282
283
**Usage Examples:**
284
285
```kotlin
286
// Work with JavaScript arrays
287
val jsArray: JsReadonlyArray<String> = js("['a', 'b', 'c']")
288
val length = jsArray.length // 3
289
val first = jsArray[0] // "a"
290
291
// Work with JavaScript sets
292
val jsSet: JsReadonlySet<String> = js("new Set(['x', 'y', 'z'])")
293
val hasX = jsSet.has("x") // true
294
val size = jsSet.size // 3
295
296
// Work with JavaScript maps
297
val jsMap: JsReadonlyMap<String, Int> = js("new Map([['a', 1], ['b', 2]])")
298
val value = jsMap.get("a") // 1
299
val hasKey = jsMap.has("b") // true
300
```
301
302
### Dynamic Iterator Support
303
304
Enable iteration over dynamic JavaScript objects.
305
306
```kotlin { .api }
307
/**
308
* Iterator support for dynamic objects
309
*/
310
operator fun dynamic.iterator(): Iterator<dynamic>
311
```
312
313
**Usage Examples:**
314
315
```kotlin
316
val jsObject = js("{ a: 1, b: 2, c: 3 }")
317
val jsArray = js("[1, 2, 3, 4, 5]")
318
319
// Iterate over JavaScript arrays
320
for (item in jsArray) {
321
console.log(item)
322
}
323
324
// Note: Object iteration depends on JavaScript object structure
325
```
326
327
## Types
328
329
```kotlin { .api }
330
// Core dynamic type
331
external interface dynamic
332
333
// External definition marker
334
external val definedExternally: Nothing
335
336
// JSON object type
337
external interface Json : dynamic
338
339
// Promise type with generic parameter
340
external class Promise<out T>
341
342
// Regular expression types
343
external class RegExp
344
external interface RegExpMatch
345
346
// JavaScript collection interfaces
347
external interface JsReadonlyArray<out E>
348
external interface JsReadonlySet<out E>
349
external interface JsReadonlyMap<K, out V>
350
```