Gap撈Tech

Kotlin Playground

Standard Playground


fun main(args: Array<String>) {
//sampleStart
    println("Hello World")
//sampleEnd
}

class & data class print difference

//sampleStart
class User(val id: Int)
data class User2(val id: Int)

fun printUser(){
    println(User(1)) // print [email protected]
    println(User2(2)) // print friendly
}
//sampleEnd

fun main(args: Array<String>) {
    printUser()
}

by lazy


fun main(args: Array<String>) {
    val a: Int by lazy { 1 }
    println(a)
}

Sealed class - Either

//sampleStart
sealed class Either<out L, out R> {
    data class Left<out T>(val value: T) : Either<T, Nothing>()
	data class Right<out T>(val value: T) : Either<Nothing, T>()
}

data class User(val id: Int)

fun someFunctionWillRun(){
    val e: Either<Throwable,User> = Either.Right(User(13579))
    when(e) {
        is Either.Left -> println(e.value)
        is Either.Right -> println(e.value.id)
        // becoz of sealed class, no need `else` case
    }
}


//sampleEnd

fun main(args: Array<String>) {
    someFunctionWillRun()
}

Coroutine Playground

import kotlinx.coroutines.experimental.*
import java.util.Random

fun main(args: Array<String>) = runBlocking {
//sampleStart
    launch {
        delay(Random().nextInt(100))
        println("A")
    }
    launch {
        delay(Random().nextInt(100))
        println("B")
    }
    
    println("Hello World")
//sampleEnd
    delay(200)
}
import kotlinx.coroutines.experimental.*
import java.util.Random

fun main(args: Array<String>) = runBlocking {
//sampleStart
    async {
        delay(Random().nextInt(100))
        println("A")
    }.await()
    
    // start after "A" is printed
    async {
        delay(Random().nextInt(100))
        println("B")
    }.await()
    
    // start after "A", "B" are printed
    println("Hello World")
//sampleEnd
}
import kotlinx.coroutines.experimental.*
import java.util.Random

fun main(args: Array<String>) = runBlocking {
//sampleStart
    val a = async {
        delay(100)
        println("A")
    }

    val b = async {
        delay(50)
        println("B")
    }

    // a, b are started already
    // run a new background job
    val backgroundJob = launch {
        while(true){
            println("background printing")
            delay(10)
        }
    }


    a.await()
    b.await()

    // run after a,b is finished
    backgroundJob.cancelAndJoin()
    println("Hellow World")
//sampleEnd
}