Kotlin Playground examples
# Kotlin Playground demo
## Automatic initialization
Insert a `
```
For instance following block of Kotlin code:
```txt
class Contact(val id: Int, var email: String)
fun main(args: Array) {
val contact = Contact(1, "mary@gmail.com")
println(contact.id)
}
```
Turns into:
```kotlin
class Contact(val id: Int, var email: String)
fun main(args: Array) {
val contact = Contact(1, "mary@gmail.com")
println(contact.id)
}
```
</div>
You can also change the playground theme or disable run button using `theme` and `data-highlight-only` attributes.
```html
```
```kotlin
fun main(args: Array) {
println("Hello World!")
}
```
</div>
Or theme `kotlin-dark`
```kotlin
fun main(args: Array) {
println("Hello World!")
}
```
</div>
Set another target platform with attribute `data-target-platform`.
```html
```
```kotlin
fun sum(a: Int, b: Int): Int {
return a + b
}
fun main(args: Array) {
print(sum(-1, 8))
}
```
</div>
You can use JS IR compiler also.
```html
```
```kotlin
fun mul(a: Int, b: Int): Int {
return a * b
}
fun main(args: Array) {
print(mul(-2, 4))
}
```
</div>
You can use Wasm compiler.
```html
```
```kotlin
fun mul(a: Int, b: Int): Int {
return a * b
}
fun main(args: Array) {
print(mul(-2, 4))
println(" + 7 =")
print(mul(-2, 4) + 7)
}
```
</div>
You can use Compose Wasm.
```html
```
```kotlin
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.window.CanvasBasedWindow
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
//sampleStart
@OptIn(ExperimentalComposeUiApi::class)
fun main() {
CanvasBasedWindow { App() }
}
@Composable
fun App() {
MaterialTheme {
var greetingText by remember { mutableStateOf("Hello World!") }
var showImage by remember { mutableStateOf(false) }
var counter by remember { mutableStateOf(0) }
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
Button(onClick = {
counter++
greetingText = "Compose: ${Greeting().greet()}"
showImage = !showImage
}) {
Text(greetingText)
}
AnimatedVisibility(showImage) {
Text(counter.toString())
}
}
}
}
private val platform = object : Platform {
override val name: String
get() = "Web with Kotlin/Wasm"
}
fun getPlatform(): Platform = platform
class Greeting {
private val platform = getPlatform()
fun greet(): String {
return "Hello, ${platform.name}!"
}
}
interface Platform {
val name: String
}
//sampleEnd
```
You can try Kotlin export to Swift.
```html
```
```kotlin
fun mul(a: Int, b: Int): Int {
return a * b
}
fun main(args: Array) {
print(mul(-2, 4))
println(" + 7 =")
print(mul(-2, 4) + 7)
}
```
</div>
```kotlin
fun mul(a: Int, b: Int): Int {
return a * b
}
fun main(args: Array) {
print(mul(-2, 4))
println(" + 7 =")
print(mul(-2, 4) + 7)
}
```
</div>
Use `data-target-platform` attribute with value `junit` for creating examples with tests:
```kotlin
import org.junit.Test
import org.junit.Assert
class TestExtensionFunctions() {
@Test fun testIntExtension() {
Assert.assertEquals("Rational number creation error: ", RationalNumber(4, 1), 4.r())
}
@Test fun testPairExtension() {
Assert.assertEquals("Rational number creation error: ", RationalNumber(2, 3), Pair(2, 3).r())
}
}
//sampleStart
/*
Then implement extension functions Int.r() and Pair.r() and make them convert Int and Pair to RationalNumber.
*/
fun Int.r(): RationalNumber = RationalNumber(this, 2)
fun Pair<Int, Int>.r(): RationalNumber = RationalNumber(first, second)
data class RationalNumber(val numerator: Int, val denominator: Int)
//sampleEnd
```
The test clases in this code snippet are folded away thanks to the `//sampleStart` and `//sampleEnd` comments in the code.
If you want to hide test classes completely just set the attribute `folded-button` to `false` value.
Also you can mark arbitrary code by putting it between `[mark]your code[/mark]`.
```html
```
```kotlin
import org.junit.Test
import org.junit.Assert
class TestLambdas() {
@Test fun contains() {
Assert.assertTrue("The result should be true if the collection contains an even number",
containsEven(listOf(1, 2, 3, 126, 555)))
}
@Test fun notContains() {
Assert.assertFalse("The result should be false if the collection doesn't contain an even number",
containsEven(listOf(43, 33)))
}
}
//sampleStart
/*
Pass a lambda to any function to check if the collection contains an even number.
The function any gets a predicate as an argument and returns true if there is at least one element satisfying the predicate.
*/
fun containsEven(collection: Collection): Boolean = collection.any {[mark]TODO()[/mark]}
//sampleEnd
```
</div>
Use `data-target-platform` attribute with value `canvas` for working with canvas in Kotlin:
```html
```
```kotlin
package fancylines
import org.w3c.dom.CanvasRenderingContext2D
import org.w3c.dom.HTMLCanvasElement
import kotlinx.browser.document
import kotlinx.browser.window
import kotlin.random.Random
val canvas = initalizeCanvas()
fun initalizeCanvas(): HTMLCanvasElement {
val canvas = document.createElement("canvas") as HTMLCanvasElement
val context = canvas.getContext("2d") as CanvasRenderingContext2D
context.canvas.width = window.innerWidth.toInt();
context.canvas.height = window.innerHeight.toInt();
document.body!!.appendChild(canvas)
return canvas
}
class FancyLines() {
val context = canvas.getContext("2d") as CanvasRenderingContext2D
val height = canvas.height
val width = canvas.width
var x = width * Random.nextDouble()
var y = height * Random.nextDouble()
var hue = 0;
fun line() {
context.save();
context.beginPath();
context.lineWidth = 20.0 * Random.nextDouble();
context.moveTo(x, y);
x = width * Random.nextDouble();
y = height * Random.nextDouble();
context.bezierCurveTo(width * Random.nextDouble(), height * Random.nextDouble(),
width * Random.nextDouble(), height * Random.nextDouble(), x, y);
hue += (Random.nextDouble() * 10).toInt();
context.strokeStyle = "hsl($hue, 50%, 50%)";
context.shadowColor = "white";
context.shadowBlur = 10.0;
context.stroke();
context.restore();
}
fun blank() {
context.fillStyle = "rgba(255,255,1,0.1)";
context.fillRect(0.0, 0.0, width.toDouble(), height.toDouble());
}
fun run() {
window.setInterval({ line() }, 40);
window.setInterval({ blank() }, 100);
}
}
//sampleStart
fun main(args: Array) {
FancyLines().run()
}
//sampleEnd
```
</div>
Use `data-js-libs` with a comma-separated list of URLs to specify additional javascript libraries to load.
```html
```
```kotlin
external fun moment(): dynamic
fun main() {
val startOfDay = moment().startOf("day").fromNow()
println("The start of the day was $startOfDay")
}
```
```kotlin
external fun moment(): dynamic
fun main() {
val startOfDay = moment().startOf("day").fromNow()
println("The start of the day was $startOfDay")
}
```
## Manual initialization
If you want to init Kotlin Playground manually - omit `data-selector` attribute and call it when it's needed:
```html
```
Add additional hidden files:
Put your files between `
</div>
</body>
</html>