Upgrade to Pro — share decks privately, control downloads, hide ads and more …

A tour of Standard Library

A tour of Standard Library

kotlin

Jaewe Heo

May 19, 2017
Tweet

More Decks by Jaewe Heo

Other Decks in Programming

Transcript

  1. A tour of Standard Library Jaewe Heo · Riiid! ·

    @importre May. 19, 2017 JetBrains Spring Seminar 2017
  2. ೞҊर਷ ੉ঠӝ • kotlin-stdlibܳ ੜ ࢓ಝࠁݶ ࢕੉ ਮఖ೧૓׮. • ౠ൤

    extension ೣࣻܳ ੜ ࢓ಝࠁݶ • ޖ঴ ٜ݅ ࣻ ੓ਸө?
  3. The Kotlin Standard Library provides living essentials for everyday work

    with Kotlin https://kotlinlang.org/api/latest/jvm/stdlib/index.html
  4. Agenda - Packages • kotlin • kotlin.system • kotlin.text •

    kotlin.collections / kotlin.sequences • kotlin.reflect • kotlin.jvm • kotlin.io
  5. Functions - let user?.let { // `it`਷ null੉ ইצ user

    // ࠶۟੄ ݃૑݄ чਸ ܻఢ (ৈӝࢲח Unit) println("${it.id}: ${it.name}") }
  6. Functions - apply user?.apply { // झ௏೐о user۽ ߄Պ //

    userܳ ܻఢ // Builder println("${id}: ${name}") }
  7. Functions - apply class MainFragment : BaseFragment() { // ...

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val hello = buttonHello.clicks() .map { HelloActivity::class } val counter = buttonCounter.clicks() .map { CounterActivity::class } Observable.mergeArray(hello, counter) .subscribe { start(it) } .apply { disposables.add(this) } } // ... } importre/compose-everything-with-rx-and-kotlin
  8. Functions - apply (Builder) companion object { fun instance(part: Int,

    review: Boolean = false): MyFragment { return MyFragment().apply { arguments = Bundle().apply { putInt("part", part) putBoolean("review", review) } } } }
  9. Functions - also user?.also { // apply৬ ׮ܰѱ झ௏೐ ߸ച

    হ਺ // userܳ ܻఢ println("${it.id}: ${it.name}") }
  10. Functions - with class MyActivityUI : AnkoComponent<MyActivity> { override fun

    createView(ui: AnkoContext<MyActivity>) = with(ui) { verticalLayout { val name = editText() button("Say Hello") { onClick { ctx.toast("Hello, ${name.text}!") } } } } } https://github.com/Kotlin/anko
  11. Functions - run #1 @Test fun testSomething() { run {

    val str = "Hello" assertEquals("Hello", str) } run { val str = "World" assertEquals("World", str) } }

  12. Functions - run #2 fun updateUi(item: Item) { itemView.run {

    title.text = item.title subtitle.text = item.subtitle } }
  13. Functions - takeIf / takeUnless val user = User(0, "kotlin",

    "[email protected]") val a = user.takeIf { it.id == 0L } println(a) // User(id=0, name=kotlin, [email protected]) val b = user.takeUnless { it.id == 0L } println(b) // null
  14. Array - init val array = arrayOf(1, 2, "hello", "kotlin")

    // [1, 2, hello, kotlin] val intArray = intArrayOf(1, 2, 3, 4) // [1, 2, 3, 4] val emptyArray = emptyArray<Any>() // [] val nullArray = arrayOfNulls<Any>(size = 5) // [null, null, null, null, null] val arrayWithInit = Array(5) { i -> (i * i).toString() } // [0, 1, 4, 9, 16]
  15. Array - equals @Test fun testEquals() { val a1 =

    arrayOf( 1, "hello", "kotlin", arrayOf("kotlin", "korea") ) val a2 = arrayOf( 1, "hello", "kotlin", arrayOf("kotlin", "korea") ) assertNotEquals(a1, a2) }
  16. Array - equals @Test fun testEquals() { val a1 =

    arrayOf( 1, "hello", "kotlin", arrayOf("kotlin", "korea") ) val a2 = arrayOf( 1, "hello", "kotlin", arrayOf("kotlin", "korea") ) assertTrue(a1.contentDeepEquals(a2)) }
  17. Retrofit / RxJava interface Api { companion object { val

    BASE_URL = "https://jsonplaceholder.typicode.com" } @GET("users") fun getUsers(): Observable<List<User>> }
  18. distinct val a = arrayOf(arrayOf("string"), arrayOf("string")) println(a.distinct().toJson()) // [["string"],["string"]] val

    b = listOf(listOf("string"), listOf("string")) println(b.distinct().toJson()) // [["string"]]
  19. Primitive type arrays • BooleanArray • ByteArray • CharArray •

    DoubleArray • FloatArray • IntArray • LongArray • ShortArray
  20. Primitive type arrays - xxxArrayOf() • booleanArrayOf() • byteArrayOf() •

    charArrayOf() • doubleArrayOf() • floatArrayOf() • intArrayOf() • longArrayOf() • shortArrayOf()
  21. Boxing Overhead println(measureNanoTime { val a = arrayOf(1, 4, 6,

    2, 5, 7, 2) println(a.contentToString()) }) println(measureNanoTime { val a = intArrayOf(1, 4, 6, 2, 5, 7, 2) println(a.contentToString()) })
  22. Boxing Overhead println(measureNanoTime { val a = arrayOf(1, 4, 6,

    2, 5, 7, 2) println(a.contentToString()) }) println(measureNanoTime { val a = intArrayOf(1, 4, 6, 2, 5, 7, 2) println(a.contentToString()) })
  23. Elapsed Time import kotlin.system.measureNanoTime import kotlin.system.measureTimeMillis fun main(args: Array<String>) {

    val elapsedTimeInNano = measureNanoTime { // do something... } val elapsedTimeInMilli = measureTimeMillis { // do something... } }
  24. Regex fun main(args: Array<String>) { val html = "http://kotlinlang.org".get() val

    httpUrls = "<a href=\"(http[^\"]+)\"" .toRegex() .findAll(html) .asIterable() .map { it.groupValues.last() } .joinToString("\n") println("urls\n%s".format(httpUrls)) }
  25. Regex - Output urls http://try.kotlinlang.org https://github.com/JetBrains/kotlin https://twitter.com/kotlin http://try.kotlinlang.org http://www.youtube.com/watch?v=viiDaLpPfN4 http://try.kotlinlang.org

    http://www.jetbrains.com/ http://hive.geosystems.aero/?locale=en http://prezi.com http://linkedin.com/company/bremeld https://play.google.com/store/apps/details?id=ru.evilbloodydemon.pills https://github.com/ex3ndr/telegram-tl ...
  26. [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email":

    "[email protected]", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { "name": "Romaguera-Crona", "catchPhrase": "Multi-layered client-server neural-net", "bs": "harness real-time e-markets" } }, ...
  27. associate val users = readUsers().users val m1 = users.associate {

    it.id to it } val m2 = users.associateBy(User::id) val m3 = hashMapOf<Long, User>() users.associateByTo(m3, User::id) assertEquals(m1, m2) assertEquals(m2, m3) assertEquals("Leanne Graham", m1[1]?.name)
  28. associate val users = readUsers().users val m1 = users.associate {

    it.id to it } val m2 = users.associateBy(User::id) val m3 = hashMapOf<Long, User>() users.associateByTo(m3, User::id) assertEquals(m1, m2) assertEquals(m2, m3) assertEquals("Leanne Graham", m1[1]?.name)
  29. By val users = readUsers().users val m1 = users.associate {

    it.id to it } val m2 = users.associateBy(User::id) val m3 = hashMapOf<Long, User>() users.associateByTo(m3, User::id) assertEquals(m1, m2) assertEquals(m2, m3) assertEquals("Leanne Graham", m1[1]?.name)
  30. To val users = readUsers().users val m1 = users.associate {

    it.id to it } val m2 = users.associateBy(User::id) val m3 = hashMapOf<Long, User>() users.associateByTo(m3, User::id) assertEquals(m1, m2) assertEquals(m2, m3) assertEquals("Leanne Graham", m1[1]?.name)
  31. Direct access val users = readUsers().users val m1 = users.associate

    { it.id to it } val m2 = users.associateBy(User::id) val m3 = hashMapOf<Long, User>() users.associateByTo(m3, User::id) assertEquals(m1, m2) assertEquals(m2, m3) assertEquals("Leanne Graham", m1[1]?.name)
  32. Filter val elements = listOf( Element(), TextElement(), TextElement() ) val

    textElements = elements.ofType(TextElement::class) println(textElements) // [TextElement, TextElement]
  33. ofType fun <T, R : Any> List<T>.ofType(kClass: KClass<R>): List<R> {

    return filter { kClass.isInstance(it) } .map { kClass.java.cast(it) } } http://reactivex.io/documentation/operators/filter.html
  34. Json.kt private val gson: Gson by lazy { GsonBuilder() .serializeNulls()

    .create() } fun Any.toJson(): String = gson.toJson(this)
  35. Json.kt private val tidyGson: Gson by lazy { GsonBuilder() .serializeNulls()

    .setPrettyPrinting() .create() } fun Any.toTidyJson(): String = tidyGson.toJson(this)
  36. $ javap Utils util [master] % javap Utils Warning: Binary

    file Utils contains com.importre.example.util.Utils Compiled from "Json.kt" public final class com.importre.example.util.Utils { public static final java.lang.String toJson(java.lang.Object); public static final java.lang.String toTidyJson(java.lang.Object); }
  37. $ javap Utils util [master] % javap Utils Warning: Binary

    file Utils contains com.importre.example.util.Utils Compiled from "Json.kt" public final class com.importre.example.util.Utils { public static final java.lang.String toJson(java.lang.Object); public static final java.lang.String toTidyJson(java.lang.Object); }
  38. JvmOverloads / JvmField data class MyClass @JvmOverloads constructor( val a:

    Int = 10, var b: Int = 20 ) { @JvmField var c = 20 }
  39. $ javap MyClass public final class com.importre.example.jvm.MyClass { public int

    c; public final int getA(); public final int getB(); public final void setB(int); public com.importre.example.jvm.MyClass(int, int); public com.importre.example.jvm.MyClass(int, int, int, kotlin.jvm.internal.DefaultConstructorMarker); public com.importre.example.jvm.MyClass(int); public com.importre.example.jvm.MyClass(); public final int component1(); public final int component2(); public final com.importre.example.jvm.MyClass copy(int, int); public static com.importre.example.jvm.MyClass copy$default( com.importre.example.jvm.MyClass, int, int, int, java.lang.Object); public java.lang.String toString(); public int hashCode(); public boolean equals(java.lang.Object); }
  40. $ javap MyClass public final class com.importre.example.jvm.MyClass { public int

    c; public final int getA(); public final int getB(); public final void setB(int); public com.importre.example.jvm.MyClass(int, int); public com.importre.example.jvm.MyClass(int, int, int, kotlin.jvm.internal.DefaultConstructorMarker); public com.importre.example.jvm.MyClass(int); public com.importre.example.jvm.MyClass(); public final int component1(); public final int component2(); public final com.importre.example.jvm.MyClass copy(int, int); public static com.importre.example.jvm.MyClass copy$default( com.importre.example.jvm.MyClass, int, int, int, java.lang.Object); public java.lang.String toString(); public int hashCode(); public boolean equals(java.lang.Object); }
  41. $ javap MyClass public final class com.importre.example.jvm.MyClass { public int

    c; public final int getA(); public final int getB(); public final void setB(int); public com.importre.example.jvm.MyClass(int, int); public com.importre.example.jvm.MyClass(int, int, int, kotlin.jvm.internal.DefaultConstructorMarker); public com.importre.example.jvm.MyClass(int); public com.importre.example.jvm.MyClass(); public final int component1(); public final int component2(); public final com.importre.example.jvm.MyClass copy(int, int); public static com.importre.example.jvm.MyClass copy$default( com.importre.example.jvm.MyClass, int, int, int, java.lang.Object); public java.lang.String toString(); public int hashCode(); public boolean equals(java.lang.Object); }
  42. $ javap MyClass public final class com.importre.example.jvm.MyClass { public int

    c; public final int getA(); public final int getB(); public final void setB(int); public com.importre.example.jvm.MyClass(int, int); public com.importre.example.jvm.MyClass(int, int, int, kotlin.jvm.internal.DefaultConstructorMarker); public com.importre.example.jvm.MyClass(int); public com.importre.example.jvm.MyClass(); public final int component1(); public final int component2(); public final com.importre.example.jvm.MyClass copy(int, int); public static com.importre.example.jvm.MyClass copy$default( com.importre.example.jvm.MyClass, int, int, int, java.lang.Object); public java.lang.String toString(); public int hashCode(); public boolean equals(java.lang.Object); }
  43. use public inline fun <T : Closeable?, R> T.use(block: (T)

    -> R): R { var closed = false try { return block(this) } catch (e: Exception) { closed = true try { this?.close() } catch (closeException: Exception) { } throw e } finally { if (!closed) { this?.close() } } }
  44. Kotlin • Backend • Spring • ... • Frontend •

    Web (Javascript) • Android • CLI • Native
  45. kotlin-apps ./kotlin-apps ├── backend │ ├── build.gradle │ └── src

    ├── build.gradle ├── cli │ ├── build.gradle │ └── src ├── frontend │ ├── build.gradle │ ├── src │ └── web ├── settings.gradle └── shared ├── build.gradle └── src https://github.com/importre/kotlin-apps
  46. kotlin-apps (shared) ./kotlin-apps ├── backend │ ├── build.gradle │ └──

    src ├── build.gradle ├── cli │ ├── build.gradle │ └── src ├── frontend │ ├── build.gradle │ ├── src │ └── web ├── settings.gradle └── shared ├── build.gradle └── src https://github.com/importre/kotlin-apps
  47. kotlin-apps (cli) ./kotlin-apps ├── backend │ ├── build.gradle │ └──

    src ├── build.gradle ├── cli │ ├── build.gradle │ └── src ├── frontend │ ├── build.gradle │ ├── src │ └── web ├── settings.gradle └── shared ├── build.gradle └── src https://github.com/importre/kotlin-apps
  48. kotlin-apps (backend) ./kotlin-apps ├── backend │ ├── build.gradle │ └──

    src ├── build.gradle ├── cli │ ├── build.gradle │ └── src ├── frontend │ ├── build.gradle │ ├── src │ └── web ├── settings.gradle └── shared ├── build.gradle └── src https://github.com/importre/kotlin-apps
  49. kotlin-apps (frontend) ./kotlin-apps ├── backend │ ├── build.gradle │ └──

    src ├── build.gradle ├── cli │ ├── build.gradle │ └── src ├── frontend │ ├── build.gradle │ ├── src │ └── web ├── settings.gradle └── shared ├── build.gradle └── src https://github.com/importre/kotlin-apps
  50. shared fun greeting(user: User): String = "Hello, ${user.name}!" data class

    User( val name: String = "Kotlin" ) https://github.com/importre/kotlin-apps
  51. cli fun main(args: Array<String>) { val message = greeting(User()) println(message)

    // Hello, Kotlin! } https://github.com/importre/kotlin-apps
  52. cli (hello-kotlin) $ hello-kotlin -h usage: hello-kotlin [-h] [-n NAME]

    [-v] optional arguments: -h, --help show this help message and exit -n NAME, name --name NAME -v, cli version --version $ hello-kotlin Hello, Kotlin! https://github.com/importre/hello-kotlin
  53. backend fun Application.main() { install(Routing) { get("/") { val response

    = mapOf( "message" to greeting(User()) ).toJson() call.respondText(response, ContentType.Application.Json) } } } https://github.com/importre/kotlin-apps
  54. frontend <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Frontend</title> <script

    type="text/javascript" src="js/lib/kotlin.js"></script> </head> <body> <div id="main"></div> <script type="text/javascript" src="js/app.js"></script> </body> </html> https://github.com/importre/kotlin-apps
  55. frontend fun main(args: Array<String>) { val message = "Hello, Javascript!"

    println(message) document.body ?.querySelector("#main") ?.innerHTML = message } https://github.com/importre/kotlin-apps
  56. Summary • Ե э਷ APIо ݆णפ׮ • बबೡ ٸ API

    ޙࢲ വযࠁইਃ • ௏٘ܳ ҕਬೞৈ ੤ࢎਊ ೧ࠇद׮ ♻