0
# Platform Services
1
2
I/O operations, time management, random number generation, UUID support, and reflection services optimized for WebAssembly platform.
3
4
## Capabilities
5
6
### I/O Operations
7
8
Console output operations for WebAssembly applications.
9
10
```kotlin { .api }
11
/**
12
* Prints line separator to standard output
13
*/
14
fun println()
15
16
/**
17
* Prints given message and line separator to standard output
18
* @param message Message to print (can be any type)
19
*/
20
fun println(message: Any?)
21
22
/**
23
* Prints given message to standard output
24
* @param message Message to print (can be any type)
25
*/
26
fun print(message: Any?)
27
28
/**
29
* Throws UnsupportedOperationException (not supported in K/Wasm)
30
* @return String (never returns)
31
* @throws UnsupportedOperationException Always thrown
32
*/
33
fun readln(): String
34
35
/**
36
* Throws UnsupportedOperationException (not supported in K/Wasm)
37
* @return String? (never returns)
38
* @throws UnsupportedOperationException Always thrown
39
*/
40
fun readlnOrNull(): String?
41
```
42
43
**Usage Examples:**
44
45
```kotlin
46
// Basic console output
47
println("Hello, WebAssembly!")
48
println(42)
49
println(listOf("a", "b", "c"))
50
51
print("Loading")
52
print(".")
53
print(".")
54
print(".")
55
println(" Done!")
56
57
// Note: Input operations are not supported
58
try {
59
val input = readln() // This will throw UnsupportedOperationException
60
} catch (e: UnsupportedOperationException) {
61
println("Input not supported in WebAssembly")
62
}
63
```
64
65
### Time Support
66
67
Time and duration handling with monotonic time source and instant support.
68
69
```kotlin { .api }
70
/**
71
* Monotonic time source using performance.now() or Date.now()
72
*/
73
object MonotonicTimeSource : TimeSource.WithComparableMarks {
74
/**
75
* Creates time mark for current moment
76
* @return ValueTimeMark Time mark representing current time
77
*/
78
fun markNow(): ValueTimeMark
79
80
/**
81
* Calculates elapsed duration from given time mark
82
* @param timeMark Starting time mark
83
* @return Duration Elapsed time duration
84
*/
85
fun elapsedFrom(timeMark: ValueTimeMark): Duration
86
87
/**
88
* Adjusts time mark by given duration
89
* @param timeMark Original time mark
90
* @param duration Duration to adjust by
91
* @return ValueTimeMark Adjusted time mark
92
*/
93
fun adjustReading(timeMark: ValueTimeMark, duration: Duration): ValueTimeMark
94
95
/**
96
* Calculates difference between two time marks
97
* @param one First time mark
98
* @param another Second time mark
99
* @return Duration Difference between time marks
100
*/
101
fun differenceBetween(one: ValueTimeMark, another: ValueTimeMark): Duration
102
}
103
104
/**
105
* Gets current system time as Instant
106
* @return Instant Current system time
107
*/
108
fun systemClockNow(): Instant
109
110
/**
111
* Throws UnsupportedOperationException (serialization only supported in K/JVM)
112
* @param instant Instant to serialize
113
* @return Any (never returns)
114
* @throws UnsupportedOperationException Always thrown
115
*/
116
internal fun serializedInstant(instant: Instant): Any
117
118
/**
119
* Formats double value to exact number of decimal places
120
* @param value Double value to format
121
* @param decimals Number of decimal places
122
* @return String Formatted string representation
123
*/
124
internal fun formatToExactDecimals(value: Double, decimals: Int): String
125
126
/**
127
* Always true for duration assertions
128
*/
129
internal val durationAssertionsEnabled: Boolean
130
131
/**
132
* Represents time mark reading as Double
133
*/
134
internal typealias ValueTimeMarkReading = Double
135
```
136
137
**Usage Examples:**
138
139
```kotlin
140
import kotlin.time.*
141
142
// Measure execution time
143
val timeSource = TimeSource.Monotonic
144
val startMark = timeSource.markNow()
145
146
// Perform some operation
147
repeat(1000000) {
148
// Some work
149
}
150
151
val elapsed = timeSource.elapsedFrom(startMark)
152
println("Operation took: $elapsed")
153
154
// Work with instants
155
val now = Clock.System.now()
156
println("Current time: $now")
157
158
// Duration formatting
159
val duration = 1.5.seconds
160
println("Duration: ${duration.toString()}")
161
```
162
163
### Random Number Generation
164
165
Platform-specific random number generation using JavaScript Math.random().
166
167
```kotlin { .api }
168
/**
169
* Creates default platform Random instance using JavaScript Math.random()
170
* @return Random Platform-specific random number generator
171
*/
172
fun defaultPlatformRandom(): Random
173
```
174
175
**Usage Examples:**
176
177
```kotlin
178
import kotlin.random.Random
179
180
// Use default platform random
181
val random = Random.Default
182
println("Random int: ${random.nextInt()}")
183
println("Random double: ${random.nextDouble()}")
184
println("Random boolean: ${random.nextBoolean()}")
185
186
// Random in range
187
println("Random 1-10: ${random.nextInt(1, 11)}")
188
println("Random 0.0-1.0: ${random.nextDouble(0.0, 1.0)}")
189
190
// Random collection operations
191
val items = listOf("apple", "banana", "cherry", "date")
192
println("Random item: ${items.random()}")
193
194
val shuffled = items.shuffled()
195
println("Shuffled: $shuffled")
196
```
197
198
### UUID Support
199
200
Cryptographically secure UUID generation using browser crypto APIs.
201
202
```kotlin { .api }
203
/**
204
* Generates cryptographically secure random UUID using crypto.getRandomValues
205
* @return Uuid Cryptographically secure random UUID
206
*/
207
fun secureRandomUuid(): Uuid
208
```
209
210
**Usage Examples:**
211
212
```kotlin
213
import kotlin.uuid.Uuid
214
215
// Generate secure random UUIDs
216
val uuid1 = Uuid.random()
217
println("UUID 1: $uuid1")
218
219
val uuid2 = Uuid.random()
220
println("UUID 2: $uuid2")
221
222
// UUIDs are unique
223
println("UUIDs are different: ${uuid1 != uuid2}")
224
225
// Work with UUID properties
226
println("UUID string: ${uuid1.toString()}")
227
println("UUID bytes: ${uuid1.toByteArray().contentToString()}")
228
229
// Parse UUID from string
230
val uuidString = "550e8400-e29b-41d4-a716-446655440000"
231
val parsedUuid = Uuid.parse(uuidString)
232
println("Parsed UUID: $parsedUuid")
233
```
234
235
### Reflection Support
236
237
Reflection support for external JavaScript classes and Kotlin objects.
238
239
```kotlin { .api }
240
/**
241
* KClass implementation for external JavaScript classes
242
* @param T Type of the external class
243
*/
244
internal class KExternalClassImpl<T : Any> : KClass<T> {
245
/**
246
* Simple class name from JavaScript constructor
247
*/
248
val simpleName: String?
249
250
/**
251
* Always null for external classes
252
*/
253
val qualifiedName: String?
254
255
/**
256
* Checks if value is instance using JavaScript instanceof
257
* @param value Value to check
258
* @return Boolean Whether value is instance of this class
259
*/
260
fun isInstance(value: Any?): Boolean
261
262
/**
263
* Compare JavaScript constructors
264
* @param other Other object to compare
265
* @return Boolean Whether objects are equal
266
*/
267
override fun equals(other: Any?): Boolean
268
269
/**
270
* Hash based on simple name
271
* @return Int Hash code
272
*/
273
override fun hashCode(): Int
274
275
/**
276
* String representation
277
* @return String String representation of the class
278
*/
279
override fun toString(): String
280
}
281
282
/**
283
* Gets KClass for given object, handling both Kotlin and JavaScript external objects
284
* @param obj Object to get KClass for
285
* @return KClass<T> KClass instance for the object
286
*/
287
internal fun <T : Any> getKClassForObject(obj: Any): KClass<T>
288
```
289
290
**Usage Examples:**
291
292
```kotlin
293
import kotlin.reflect.KClass
294
295
// Get KClass for Kotlin objects
296
data class User(val name: String, val age: Int)
297
val user = User("Alice", 25)
298
val userClass: KClass<User> = user::class
299
300
println("Class name: ${userClass.simpleName}")
301
println("Is instance: ${userClass.isInstance(user)}")
302
303
// Work with external JavaScript classes
304
@JsName("Date")
305
external class JsDate : JsAny {
306
fun getTime(): Double
307
}
308
309
val jsDate = js("new Date()") as JsDate
310
val jsDateClass = jsDate::class
311
312
println("JS Class name: ${jsDateClass.simpleName}")
313
println("Is JS Date: ${jsDateClass.isInstance(jsDate)}")
314
```
315
316
## Platform Integration Patterns
317
318
### Performance Monitoring
319
320
```kotlin
321
import kotlin.time.*
322
323
class PerformanceMonitor {
324
private val timeSource = TimeSource.Monotonic
325
326
fun <T> measureTime(operation: () -> T): Pair<T, Duration> {
327
val startMark = timeSource.markNow()
328
val result = operation()
329
val elapsed = timeSource.elapsedFrom(startMark)
330
return result to elapsed
331
}
332
333
fun benchmark(name: String, iterations: Int, operation: () -> Unit) {
334
println("Benchmarking $name...")
335
val times = mutableListOf<Duration>()
336
337
repeat(iterations) {
338
val (_, elapsed) = measureTime(operation)
339
times.add(elapsed)
340
}
341
342
val average = times.map { it.inWholeNanoseconds }.average().nanoseconds
343
val min = times.minOrNull() ?: Duration.ZERO
344
val max = times.maxOrNull() ?: Duration.ZERO
345
346
println("$name results:")
347
println(" Average: $average")
348
println(" Min: $min")
349
println(" Max: $max")
350
}
351
}
352
353
// Usage
354
val monitor = PerformanceMonitor()
355
356
monitor.benchmark("Array sort", 1000) {
357
val array = IntArray(1000) { Random.nextInt() }
358
array.sort()
359
}
360
```
361
362
### Logging System
363
364
```kotlin
365
enum class LogLevel { DEBUG, INFO, WARN, ERROR }
366
367
class Logger(private val name: String) {
368
fun log(level: LogLevel, message: String, vararg args: Any?) {
369
val timestamp = Clock.System.now()
370
val formattedMessage = if (args.isNotEmpty()) {
371
message.format(*args)
372
} else {
373
message
374
}
375
376
println("[$timestamp] ${level.name} $name: $formattedMessage")
377
}
378
379
fun debug(message: String, vararg args: Any?) = log(LogLevel.DEBUG, message, *args)
380
fun info(message: String, vararg args: Any?) = log(LogLevel.INFO, message, *args)
381
fun warn(message: String, vararg args: Any?) = log(LogLevel.WARN, message, *args)
382
fun error(message: String, vararg args: Any?) = log(LogLevel.ERROR, message, *args)
383
}
384
385
// Usage
386
val logger = Logger("MyApp")
387
logger.info("Application started")
388
logger.warn("This is a warning with value: %d", 42)
389
logger.error("Something went wrong!")
390
```
391
392
### Unique ID Generation
393
394
```kotlin
395
class IdGenerator {
396
private val random = Random.Default
397
398
fun generateShortId(): String {
399
return (1..8)
400
.map { "0123456789abcdefghijklmnopqrstuvwxyz".random(random) }
401
.joinToString("")
402
}
403
404
fun generateUuid(): String {
405
return Uuid.random().toString()
406
}
407
408
fun generateTimestampId(): String {
409
val timestamp = Clock.System.now().toEpochMilliseconds()
410
val randomSuffix = random.nextInt(1000, 9999)
411
return "${timestamp}-${randomSuffix}"
412
}
413
}
414
415
// Usage
416
val idGen = IdGenerator()
417
println("Short ID: ${idGen.generateShortId()}")
418
println("UUID: ${idGen.generateUuid()}")
419
println("Timestamp ID: ${idGen.generateTimestampId()}")
420
```