SlideShare ist ein Scribd-Unternehmen logo
1 von 45
Downloaden Sie, um offline zu lesen
The Kotlin
Programming Language

       Andrey Breslav
What is Kotlin?
•   Statically typed
•   JVM-targeted
•   general-purpose programming language
•   developed by JetBrains
    ➡   intended for industrial use



•   Docs available today
•   Public preview version coming soon

                               2
Motivation: our situation
• Huge Java codebase (>50k classes, 10
  years old)
• Want a modern expressive language
  ➡   that's easy to use with what we have

• Need efficient tooling
• None of the existing languages
  was a good fit

                        3
Design goals
• Full Java interoperability
• Compiles as fast as Java
• More concise than Java
• Prevents more errors than Java
• Way simpler than Scala

                  4
Innovation
• Not a research project
• Focus on common sence
• Learning from others
  ➡   Groovy, C#, Scala, Gosu...




                        5
Tooling
• Compiler
  ➡   Open Source, Apache 2
• IntelliJ IDEA plugin
  ➡   Developed in parallel with the compiler
  ➡   Open Source
• Basic Eclipse plugin
  ➡   Open Source


                          10
Features: Traditional
• Properties
• First-class functions (closures)
• Pattern matching
• Operator overloading
• Local type inference




                       10
Features: Distinguishing
• Traits ("code in interfaces")
• Extension functions
• Static null-safety guarantees
• Smart casts after type checks
• Inline functions (zero-overhead closures)
• Reified generics
• First-class delegation
• Build infrastructure (modules) as part of the language
                           11
Code examples




      9
Hello, world!
namespace hello

fun main(args : Array<String>) : Unit {
  println("Hello, world!")
}

fun println(message : String) {
    System.out?.println(message)
}




                           10
Hello, <names>!
fun main(args : Array<String>) {
    var names = ""

    for (i in args.indices) {
        names += args[i]
        if (i + 1 < args.size)
            names += ", "
    }

    println("Hello, $names!")
}

val Array<*>.indices : Iterable<Int>
  get() = IntRange<Int>(0, size - 1)




                           11
Hello, <names>! (Faster version)
fun main(args : Array<String>) {
    val names = StringBuilder()

    for (i in args.indices) {
        names += args[i]
        if (i + 1 < args.size)
            names += ", "
    }

    println("Hello, $names!")
}

fun StringBuilder.plusAssign(s : String) {
    this.append(s)
}



                           12
Hello, <names>! (Realistic version)
fun main(args : Array<String>) {
    println("Hello, ${args.join(", ")}!")
}




                           13
join() and iterate()
fun <T> Iterable<T>.join(separator : String) : String {
    val names = StringBuilder()
    this.iterate { name, hasNext =>
        names += name
        if (hasNext)
            names += separator
    }
    return names.toString()
}

fun <T> Iterable<T>.iterate(f : fun(T, Boolean)) {
    val it = iterator()
    while (it.hasNext()) {
        f(it.next(), it.hasNext())
    }
}


                            14
Null-safety
fun parseInt(s   : String) : Int? {
    try {
        return   Integer.parseInt(s)
    } catch (e   : NumberFormatException) {
        return   null
    }
}

fun main(args : Array<String>) {
    val x = parseInt("123")
    val y = parseInt("Hello")
    print(x?.times(2))        // Can't say: print(x * 2)

    if (x != null) {
        print(x * 2)
    }
}
                             15
Mapping to Java types
    Kotlin     GEN    Java     LOAD      Kotlin
     Any             Object              Any?
    Unit              void               Unit
     Int              int                 Int
    Int?             Integer             Int?
   String            String             String?
  Array<Foo>         Foo[]            Array<Foo?>?
  IntArray           int[]             IntArray?
   Nothing             -                   -
     Foo              Foo                Foo?


                       16
Mapping to Java types
    Kotlin     GEN    Java     LOAD      Kotlin
     Any             Object              Any?
    Unit              void               Unit
     Int              int                 Int
    Int?             Integer             Int?
   String            String             String?
  Array<Foo>         Foo[]            Array<Foo?>?
  IntArray           int[]             IntArray?
   Nothing             -                   -
     Foo              Foo                Foo?


                       17
Mapping to Java types
    Kotlin     GEN    Java     LOAD      Kotlin
     Any             Object              Any?
    Unit              void               Unit
     Int              int                 Int
    Int?             Integer             Int?
   String            String             String?
  Array<Foo>         Foo[]            Array<Foo?>?
  IntArray           int[]             IntArray?
   Nothing             -                   -
     Foo              Foo                Foo?


                       18
Smart casts and When
fun foo(obj : Any?) {
    if (obj is String) {
      obj.substring(2)
    }
    when (obj) {
        is String => obj[0]
        is Int => obj + 1
        !is Boolean => null
        else => ...
    }
}




                              19
More on when-expressions
fun bar(x : Int) {
    when (x) {
        0 => "Zero"
        1, 2, 3 => "1, 2 or 3"
        x + 1 => "Really strange"
        in 10..100 => "In range"
        !in 100..1000 => "Out of range"
    }
}




                           20
Classes
  open class Parent(p : Bar) {
      open fun foo() {}
      fun bar() {}
  }

  class Child(p : Bar) : Parent(p) {
      override fun foo() {}
  }


• Any is the default supertype
• Constructors must initialize supertypes
• Final by default, explicit override annotations

                          21
Traits
trait T1 : Class1, OtherTrait {
    // No state
    fun foo() : Int = 1 // open by default
    fun bar() : Int     // abstract by default
}


class Foo(p : Bar) : Class1(p), T1, T2 {
  override fun bar() : Int = foo() + 1
}


                        22
Disambiguation
trait A {
    fun foo() : Int = 1
}


open class B() {
    open fun foo() : Int = 2
}


class C() : B(), A {
    override fun foo() = super<A>.foo()
}



                               23
First-class Delegation
trait List<T> {
    fun add(t : T)
    fun get(index : Int) : T
}


class ListDecorator<T>(p : List<T>) : List<T> by p {
    override fun add(t : T) {
        log.message("Added $t")
         super.add(t)
    }


    // override fun get(index : Int) : T = p.get()
}




                                    24
First-class functions
•   Functions
    ➡   fun f(p : Int) : String

•   Function types
    ➡   fun (p : Int) : String
    ➡   fun (Int) : String

•   Function literals
    ➡   {p => p.toString()}
    ➡   {(p : Int) => p.toString()}
    ➡   {(p : Int) : String => p.toString()}


                             25
Higher-order functions
fun <T> filter(
          c : Iterable<T>,
          f : fun(T) : Boolean) : Iterable<T>

• filter(list,         {s => s.length < 3})
  ➡   Sugar: last function literal argument
      ✦   filter(list) {s => s.length < 3}
  ➡   Sugar: one-parameter function literal
      ✦   filter(list) { it.length < 3 }


                          26
Infix function calls & "LINQ"
a.contains(b)

// is the same as

a contains b



users

   .filter { it hasPrivilege WRITE }

   .map { it => it.fullName }

   .orderBy { lastName }


                      27
Lock example (I)
myLock.lock()
try {
    // Do something
}
finally {
    myLock.unlock()
}




                      28
Lock example (II)

lock(myLock) {
    // Do something
}




fun lock(l : Lock, body : fun () : Unit)


                       29
Lock example (III)
inline fun lock(l : Lock, body : fun () : Unit) {
    l.lock()
    try {
        body()
    }
    finally {
        l.unlock()
    }
}


                       30
Extension functions
•   Functions
    ➡   fun Foo.f(p : Int) : String

•   Function types
    ➡   fun Foo.(p : Int) : String
    ➡   fun Foo.(Int) : String

•   Function literals
    ➡   {Foo.(p : Int) => this.toString()}
    ➡   {Foo.(p : Int) : String => this.toString()}



                         31
Builders in Groovy
html {
    head {
        title "XML encoding with Groovy"
    }
    body {
        h1 "XML encoding with Groovy"
        p "this format can be used as an alternative markup to XML"


        /* an element with attributes and text content */
        ahref:'http://groovy.codehaus.org' ["Groovy"]
    }
}



                                  32
Builders in Kotlin
html {
    head {
        title { +"XML encoding with Kotlin" }
    }
    body {
        h1 { +"XML encoding with Kotlin" }
        p { +"this format is now type-safe" }


        /* an element with attributes and text content */
        a(href="http://jetbrains.com/kotlin") { +"Kotlin" }
    }
}



                                  33
Builders: Implementation (I)
•   Function definition

    fun html(init : fun HTML.() : Unit) : HTML {
      val html = HTML()
      html.init()
      return html
    }
•   Usage

    html {
      this.head { ... }
    }


                          34
Builders: Implementation (II)
•   Function definition

    fun html(init : fun HTML.() : Unit) : HTML {
      val html = HTML()
      html.init()
      return html
    }
•   Usage

    html {
      head { ... }
    }


                          35
Builders: Implementation (III)
abstract class Tag(val name : String) : Element {
    val children = ArrayList<Element>()
    val attributes = HashMap<String, String>()
}

abstract class TagWithText(name : String) : Tag(name) {
    fun String.plus() {
      children.add(TextElement(this))
    }
}

class HTML() : Tag("html") {
    fun head(init : fun Head.() : Unit) { }
    fun body(init : fun Body.() : Unit) { }
}



                           36
Builders in Kotlin
html {
    head {
        title { +"XML encoding with Kotlin" }
    }
    body {
        h1 { +"XML encoding with Kotlin" }
        p { +"this format is now type-safe" }


        /* an element with attributes and text content */
        a(href="http://jetbrains.com/kotlin") { +"Kotlin" }
    }
}



                                  37
Generics: Invariance
class List<T> {
    fun add(t : T)
    fun get(index : Int) : T
}


val ints = List<Int>()
val anys : List<Any> = ints
anys.add("1") // Cause of the problem
val i : Int = ints.get(0) // !!!
                       38
Generics: Declaration-site variance
class List<T> {           List<Int> >:< List<Any>
    fun add(t : T)        val ints = List<Int>()
    fun get() : T         val anys : List<Any> = ints
}




class Producer<out T> {   val ints = Producer<Int>()
    fun get() : T         val anys : Producer<Any> = ints
}


class Consumer<in T> {    val anys = Consumer<Any>()
    fun add(t : T)        val ints : Consumer<Int> = anys
}



                             39
Generics: Use-site variance
val ints = List<Int>()
val anysOut : List<out Any> = ints
anysOut.add("1") // Not available
val i : Int = ints.get() // No problem

val anys = List<Any>()
val intsIn : List<in Int> = anys
intsIn.add(0)
val obj = intsIn.get() // : Any?

                     40
Reified generics
• Type information in retained at runtime
  ➡   foo is List<T>
  ➡   Array<T>(3)
  ➡   T.create()

• Java types are still erased
  ➡   foo is java.util.List<*>



                    41
Class objects (I)
• Classes have no static members
• Each class may have a class object
  associated to it:
     class Example() {
         class object {
             fun create() = Example()
         }
     }

     val e = Example.create()




                        42
Class objects (II)
• Class objects can have supertypes:
     class Example() {
         class object : Factory<Example> {
             override fun create() = Example()
         }
     }

     val factory : Factory<Example> = Example
     val e : Example = factory.create()




                       43
Class objects (III)
• Generic constraints for class objects:
     class Lazy<T>()
       where class object T : Factory<T>
     {
       private var store : T? = null
       public val value : T
         get() {
           if (store == null) {
             store = T.create()
           }
           return store
         }
     }



                        44
Resources
• Documentation:
 ➡   http://jetbrains.com/kotlin

• Blog:
 ➡   http://blog.jetbrains.com/kotlin

• Twitter:
 ➡   @project_kotlin
 ➡   @abreslav

                         45

Weitere ähnliche Inhalte

Was ist angesagt?

Taking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyTaking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyHaim Yadid
 
Language Design Trade-offs
Language Design Trade-offsLanguage Design Trade-offs
Language Design Trade-offsAndrey Breslav
 
Future of Kotlin - How agile can language development be?
Future of Kotlin - How agile can language development be?Future of Kotlin - How agile can language development be?
Future of Kotlin - How agile can language development be?Andrey Breslav
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin XPeppers
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformEastBanc Tachnologies
 
Kotlin boost yourproductivity
Kotlin boost yourproductivityKotlin boost yourproductivity
Kotlin boost yourproductivitynklmish
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in actionCiro Rizzo
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsBartosz Kosarzycki
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoMuhammad Abdullah
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017Hardik Trivedi
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devsAdit Lal
 
Building microservices with Kotlin
Building microservices with KotlinBuilding microservices with Kotlin
Building microservices with KotlinHaim Yadid
 
Coding for Android on steroids with Kotlin
Coding for Android on steroids with KotlinCoding for Android on steroids with Kotlin
Coding for Android on steroids with KotlinKai Koenig
 
Kotlin for Android Developers - 1
Kotlin for Android Developers - 1Kotlin for Android Developers - 1
Kotlin for Android Developers - 1Mohamed Nabil, MSc.
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to KotlinMagda Miu
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainersSunghyouk Bae
 

Was ist angesagt? (20)

Taking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyTaking Kotlin to production, Seriously
Taking Kotlin to production, Seriously
 
Language Design Trade-offs
Language Design Trade-offsLanguage Design Trade-offs
Language Design Trade-offs
 
Future of Kotlin - How agile can language development be?
Future of Kotlin - How agile can language development be?Future of Kotlin - How agile can language development be?
Future of Kotlin - How agile can language development be?
 
Kotlin Overview
Kotlin OverviewKotlin Overview
Kotlin Overview
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platform
 
Kotlin boost yourproductivity
Kotlin boost yourproductivityKotlin boost yourproductivity
Kotlin boost yourproductivity
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in action
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devs
 
Building microservices with Kotlin
Building microservices with KotlinBuilding microservices with Kotlin
Building microservices with Kotlin
 
Coding for Android on steroids with Kotlin
Coding for Android on steroids with KotlinCoding for Android on steroids with Kotlin
Coding for Android on steroids with Kotlin
 
Exploring Kotlin
Exploring KotlinExploring Kotlin
Exploring Kotlin
 
Kotlin for Android Developers - 1
Kotlin for Android Developers - 1Kotlin for Android Developers - 1
Kotlin for Android Developers - 1
 
Java Full Throttle
Java Full ThrottleJava Full Throttle
Java Full Throttle
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to Kotlin
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainers
 

Andere mochten auch

最新AndroidとIoTプラットフォームの今 (WJ2016)
最新AndroidとIoTプラットフォームの今 (WJ2016)最新AndroidとIoTプラットフォームの今 (WJ2016)
最新AndroidとIoTプラットフォームの今 (WJ2016)嶋 是一 (Yoshikazu SHIMA)
 
Kotlin/Golang Developer seminor. 「Androidが生み出す開発言語の多様性」 リックテレコム主催
Kotlin/Golang Developer seminor. 「Androidが生み出す開発言語の多様性」 リックテレコム主催Kotlin/Golang Developer seminor. 「Androidが生み出す開発言語の多様性」 リックテレコム主催
Kotlin/Golang Developer seminor. 「Androidが生み出す開発言語の多様性」 リックテレコム主催嶋 是一 (Yoshikazu SHIMA)
 
Kotlin for Android: Brief and Clear
Kotlin for Android: Brief and ClearKotlin for Android: Brief and Clear
Kotlin for Android: Brief and ClearAndrey Breslav
 
Kotlin: Incompetence * Motivation = Innovation?
Kotlin: Incompetence * Motivation = Innovation?Kotlin: Incompetence * Motivation = Innovation?
Kotlin: Incompetence * Motivation = Innovation?Andrey Breslav
 
JavaOne2012: Kotlin: Practical Aspects of JVM Language Implementation
JavaOne2012: Kotlin: Practical Aspects of JVM Language ImplementationJavaOne2012: Kotlin: Practical Aspects of JVM Language Implementation
JavaOne2012: Kotlin: Practical Aspects of JVM Language ImplementationAndrey Breslav
 
Kotlin (Introduction for students)
Kotlin (Introduction for students)Kotlin (Introduction for students)
Kotlin (Introduction for students)Andrey Breslav
 
Kotlin gets Reflection
Kotlin gets ReflectionKotlin gets Reflection
Kotlin gets ReflectionAndrey Breslav
 
[JVMLS 12] Kotlin / Java Interop
[JVMLS 12] Kotlin / Java Interop[JVMLS 12] Kotlin / Java Interop
[JVMLS 12] Kotlin / Java InteropAndrey Breslav
 
Kotlin @ StrangeLoop 2011
Kotlin @ StrangeLoop 2011Kotlin @ StrangeLoop 2011
Kotlin @ StrangeLoop 2011Andrey Breslav
 
Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Andrey Breslav
 
Kotlin @ CSClub & Yandex
Kotlin @ CSClub & YandexKotlin @ CSClub & Yandex
Kotlin @ CSClub & YandexAndrey Breslav
 
Flexible Types in Kotlin - JVMLS 2015
Flexible Types in Kotlin - JVMLS 2015Flexible Types in Kotlin - JVMLS 2015
Flexible Types in Kotlin - JVMLS 2015Andrey Breslav
 
Introduction to Kotlin: Brief and clear
Introduction to Kotlin: Brief and clearIntroduction to Kotlin: Brief and clear
Introduction to Kotlin: Brief and clearAndrey Breslav
 
JVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinJVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinAndrey Breslav
 
Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»e-Legion
 
Be More Productive with Kotlin
Be More Productive with KotlinBe More Productive with Kotlin
Be More Productive with KotlinBrandon Wever
 
Kotlinソースコード探訪
Kotlinソースコード探訪Kotlinソースコード探訪
Kotlinソースコード探訪yy yank
 

Andere mochten auch (20)

最新AndroidとIoTプラットフォームの今 (WJ2016)
最新AndroidとIoTプラットフォームの今 (WJ2016)最新AndroidとIoTプラットフォームの今 (WJ2016)
最新AndroidとIoTプラットフォームの今 (WJ2016)
 
Kotlin/Golang Developer seminor. 「Androidが生み出す開発言語の多様性」 リックテレコム主催
Kotlin/Golang Developer seminor. 「Androidが生み出す開発言語の多様性」 リックテレコム主催Kotlin/Golang Developer seminor. 「Androidが生み出す開発言語の多様性」 リックテレコム主催
Kotlin/Golang Developer seminor. 「Androidが生み出す開発言語の多様性」 リックテレコム主催
 
Kotlin
KotlinKotlin
Kotlin
 
Fun with Kotlin
Fun with KotlinFun with Kotlin
Fun with Kotlin
 
Functions and data
Functions and dataFunctions and data
Functions and data
 
Kotlin for Android: Brief and Clear
Kotlin for Android: Brief and ClearKotlin for Android: Brief and Clear
Kotlin for Android: Brief and Clear
 
Kotlin: Incompetence * Motivation = Innovation?
Kotlin: Incompetence * Motivation = Innovation?Kotlin: Incompetence * Motivation = Innovation?
Kotlin: Incompetence * Motivation = Innovation?
 
JavaOne2012: Kotlin: Practical Aspects of JVM Language Implementation
JavaOne2012: Kotlin: Practical Aspects of JVM Language ImplementationJavaOne2012: Kotlin: Practical Aspects of JVM Language Implementation
JavaOne2012: Kotlin: Practical Aspects of JVM Language Implementation
 
Kotlin (Introduction for students)
Kotlin (Introduction for students)Kotlin (Introduction for students)
Kotlin (Introduction for students)
 
Kotlin gets Reflection
Kotlin gets ReflectionKotlin gets Reflection
Kotlin gets Reflection
 
[JVMLS 12] Kotlin / Java Interop
[JVMLS 12] Kotlin / Java Interop[JVMLS 12] Kotlin / Java Interop
[JVMLS 12] Kotlin / Java Interop
 
Kotlin @ StrangeLoop 2011
Kotlin @ StrangeLoop 2011Kotlin @ StrangeLoop 2011
Kotlin @ StrangeLoop 2011
 
Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011
 
Kotlin @ CSClub & Yandex
Kotlin @ CSClub & YandexKotlin @ CSClub & Yandex
Kotlin @ CSClub & Yandex
 
Flexible Types in Kotlin - JVMLS 2015
Flexible Types in Kotlin - JVMLS 2015Flexible Types in Kotlin - JVMLS 2015
Flexible Types in Kotlin - JVMLS 2015
 
Introduction to Kotlin: Brief and clear
Introduction to Kotlin: Brief and clearIntroduction to Kotlin: Brief and clear
Introduction to Kotlin: Brief and clear
 
JVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinJVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in Kotlin
 
Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»
 
Be More Productive with Kotlin
Be More Productive with KotlinBe More Productive with Kotlin
Be More Productive with Kotlin
 
Kotlinソースコード探訪
Kotlinソースコード探訪Kotlinソースコード探訪
Kotlinソースコード探訪
 

Ähnlich wie Kotlin @ Devoxx 2011

2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdfAndrey Breslav
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Mohamed Nabil, MSc.
 
Kotlin Austin Droids April 14 2016
Kotlin Austin Droids April 14 2016Kotlin Austin Droids April 14 2016
Kotlin Austin Droids April 14 2016DesertJames
 
Why Kotlin makes Java null and void
Why Kotlin makes Java null and voidWhy Kotlin makes Java null and void
Why Kotlin makes Java null and voidChetan Padia
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performanceintelliyole
 
What's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageWhat's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageDroidConTLV
 
Poniendo Kotlin en producción a palos (Kotlin in production, the hard way)
Poniendo Kotlin en producción a palos (Kotlin in production, the hard way)Poniendo Kotlin en producción a palos (Kotlin in production, the hard way)
Poniendo Kotlin en producción a palos (Kotlin in production, the hard way)Andrés Viedma Peláez
 
The Arrow Library in Kotlin
The Arrow Library in KotlinThe Arrow Library in Kotlin
The Arrow Library in KotlinGarth Gilmour
 
Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)Gesh Markov
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, SwiftYandex
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlinThijs Suijten
 
Building android apps with kotlin
Building android apps with kotlinBuilding android apps with kotlin
Building android apps with kotlinShem Magnezi
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerGarth Gilmour
 
Kotlin : Happy Development
Kotlin : Happy DevelopmentKotlin : Happy Development
Kotlin : Happy DevelopmentMd Sazzad Islam
 
Scalapeno18 - Thinking Less with Scala
Scalapeno18 - Thinking Less with ScalaScalapeno18 - Thinking Less with Scala
Scalapeno18 - Thinking Less with ScalaDaniel Sebban
 
ITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingIstanbul Tech Talks
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better JavaGarth Gilmour
 
Computer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperComputer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperDeepak Singh
 
3 kotlin vs. java- what kotlin has that java does not
3  kotlin vs. java- what kotlin has that java does not3  kotlin vs. java- what kotlin has that java does not
3 kotlin vs. java- what kotlin has that java does notSergey Bandysik
 

Ähnlich wie Kotlin @ Devoxx 2011 (20)

2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3
 
Kotlin Austin Droids April 14 2016
Kotlin Austin Droids April 14 2016Kotlin Austin Droids April 14 2016
Kotlin Austin Droids April 14 2016
 
Why Kotlin makes Java null and void
Why Kotlin makes Java null and voidWhy Kotlin makes Java null and void
Why Kotlin makes Java null and void
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance
 
What's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageWhat's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritage
 
Poniendo Kotlin en producción a palos (Kotlin in production, the hard way)
Poniendo Kotlin en producción a palos (Kotlin in production, the hard way)Poniendo Kotlin en producción a palos (Kotlin in production, the hard way)
Poniendo Kotlin en producción a palos (Kotlin in production, the hard way)
 
The Arrow Library in Kotlin
The Arrow Library in KotlinThe Arrow Library in Kotlin
The Arrow Library in Kotlin
 
Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
 
Building android apps with kotlin
Building android apps with kotlinBuilding android apps with kotlin
Building android apps with kotlin
 
Introduction to Kotlin
Introduction to KotlinIntroduction to Kotlin
Introduction to Kotlin
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin Compiler
 
Kotlin : Happy Development
Kotlin : Happy DevelopmentKotlin : Happy Development
Kotlin : Happy Development
 
Scalapeno18 - Thinking Less with Scala
Scalapeno18 - Thinking Less with ScalaScalapeno18 - Thinking Less with Scala
Scalapeno18 - Thinking Less with Scala
 
ITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function Programming
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better Java
 
Computer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperComputer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paper
 
3 kotlin vs. java- what kotlin has that java does not
3  kotlin vs. java- what kotlin has that java does not3  kotlin vs. java- what kotlin has that java does not
3 kotlin vs. java- what kotlin has that java does not
 

Kürzlich hochgeladen

WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 

Kürzlich hochgeladen (20)

WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 

Kotlin @ Devoxx 2011

  • 2. What is Kotlin? • Statically typed • JVM-targeted • general-purpose programming language • developed by JetBrains ➡ intended for industrial use • Docs available today • Public preview version coming soon 2
  • 3. Motivation: our situation • Huge Java codebase (>50k classes, 10 years old) • Want a modern expressive language ➡ that's easy to use with what we have • Need efficient tooling • None of the existing languages was a good fit 3
  • 4. Design goals • Full Java interoperability • Compiles as fast as Java • More concise than Java • Prevents more errors than Java • Way simpler than Scala 4
  • 5. Innovation • Not a research project • Focus on common sence • Learning from others ➡ Groovy, C#, Scala, Gosu... 5
  • 6. Tooling • Compiler ➡ Open Source, Apache 2 • IntelliJ IDEA plugin ➡ Developed in parallel with the compiler ➡ Open Source • Basic Eclipse plugin ➡ Open Source 10
  • 7. Features: Traditional • Properties • First-class functions (closures) • Pattern matching • Operator overloading • Local type inference 10
  • 8. Features: Distinguishing • Traits ("code in interfaces") • Extension functions • Static null-safety guarantees • Smart casts after type checks • Inline functions (zero-overhead closures) • Reified generics • First-class delegation • Build infrastructure (modules) as part of the language 11
  • 10. Hello, world! namespace hello fun main(args : Array<String>) : Unit { println("Hello, world!") } fun println(message : String) { System.out?.println(message) } 10
  • 11. Hello, <names>! fun main(args : Array<String>) { var names = "" for (i in args.indices) { names += args[i] if (i + 1 < args.size) names += ", " } println("Hello, $names!") } val Array<*>.indices : Iterable<Int> get() = IntRange<Int>(0, size - 1) 11
  • 12. Hello, <names>! (Faster version) fun main(args : Array<String>) { val names = StringBuilder() for (i in args.indices) { names += args[i] if (i + 1 < args.size) names += ", " } println("Hello, $names!") } fun StringBuilder.plusAssign(s : String) { this.append(s) } 12
  • 13. Hello, <names>! (Realistic version) fun main(args : Array<String>) { println("Hello, ${args.join(", ")}!") } 13
  • 14. join() and iterate() fun <T> Iterable<T>.join(separator : String) : String { val names = StringBuilder() this.iterate { name, hasNext => names += name if (hasNext) names += separator } return names.toString() } fun <T> Iterable<T>.iterate(f : fun(T, Boolean)) { val it = iterator() while (it.hasNext()) { f(it.next(), it.hasNext()) } } 14
  • 15. Null-safety fun parseInt(s : String) : Int? { try { return Integer.parseInt(s) } catch (e : NumberFormatException) { return null } } fun main(args : Array<String>) { val x = parseInt("123") val y = parseInt("Hello") print(x?.times(2)) // Can't say: print(x * 2) if (x != null) { print(x * 2) } } 15
  • 16. Mapping to Java types Kotlin GEN Java LOAD Kotlin Any Object Any? Unit void Unit Int int Int Int? Integer Int? String String String? Array<Foo> Foo[] Array<Foo?>? IntArray int[] IntArray? Nothing - - Foo Foo Foo? 16
  • 17. Mapping to Java types Kotlin GEN Java LOAD Kotlin Any Object Any? Unit void Unit Int int Int Int? Integer Int? String String String? Array<Foo> Foo[] Array<Foo?>? IntArray int[] IntArray? Nothing - - Foo Foo Foo? 17
  • 18. Mapping to Java types Kotlin GEN Java LOAD Kotlin Any Object Any? Unit void Unit Int int Int Int? Integer Int? String String String? Array<Foo> Foo[] Array<Foo?>? IntArray int[] IntArray? Nothing - - Foo Foo Foo? 18
  • 19. Smart casts and When fun foo(obj : Any?) { if (obj is String) { obj.substring(2) } when (obj) { is String => obj[0] is Int => obj + 1 !is Boolean => null else => ... } } 19
  • 20. More on when-expressions fun bar(x : Int) { when (x) { 0 => "Zero" 1, 2, 3 => "1, 2 or 3" x + 1 => "Really strange" in 10..100 => "In range" !in 100..1000 => "Out of range" } } 20
  • 21. Classes open class Parent(p : Bar) { open fun foo() {} fun bar() {} } class Child(p : Bar) : Parent(p) { override fun foo() {} } • Any is the default supertype • Constructors must initialize supertypes • Final by default, explicit override annotations 21
  • 22. Traits trait T1 : Class1, OtherTrait { // No state fun foo() : Int = 1 // open by default fun bar() : Int // abstract by default } class Foo(p : Bar) : Class1(p), T1, T2 { override fun bar() : Int = foo() + 1 } 22
  • 23. Disambiguation trait A { fun foo() : Int = 1 } open class B() { open fun foo() : Int = 2 } class C() : B(), A { override fun foo() = super<A>.foo() } 23
  • 24. First-class Delegation trait List<T> { fun add(t : T) fun get(index : Int) : T } class ListDecorator<T>(p : List<T>) : List<T> by p { override fun add(t : T) { log.message("Added $t") super.add(t) } // override fun get(index : Int) : T = p.get() } 24
  • 25. First-class functions • Functions ➡ fun f(p : Int) : String • Function types ➡ fun (p : Int) : String ➡ fun (Int) : String • Function literals ➡ {p => p.toString()} ➡ {(p : Int) => p.toString()} ➡ {(p : Int) : String => p.toString()} 25
  • 26. Higher-order functions fun <T> filter( c : Iterable<T>, f : fun(T) : Boolean) : Iterable<T> • filter(list, {s => s.length < 3}) ➡ Sugar: last function literal argument ✦ filter(list) {s => s.length < 3} ➡ Sugar: one-parameter function literal ✦ filter(list) { it.length < 3 } 26
  • 27. Infix function calls & "LINQ" a.contains(b) // is the same as a contains b users .filter { it hasPrivilege WRITE } .map { it => it.fullName } .orderBy { lastName } 27
  • 28. Lock example (I) myLock.lock() try { // Do something } finally { myLock.unlock() } 28
  • 29. Lock example (II) lock(myLock) { // Do something } fun lock(l : Lock, body : fun () : Unit) 29
  • 30. Lock example (III) inline fun lock(l : Lock, body : fun () : Unit) { l.lock() try { body() } finally { l.unlock() } } 30
  • 31. Extension functions • Functions ➡ fun Foo.f(p : Int) : String • Function types ➡ fun Foo.(p : Int) : String ➡ fun Foo.(Int) : String • Function literals ➡ {Foo.(p : Int) => this.toString()} ➡ {Foo.(p : Int) : String => this.toString()} 31
  • 32. Builders in Groovy html { head { title "XML encoding with Groovy" } body { h1 "XML encoding with Groovy" p "this format can be used as an alternative markup to XML" /* an element with attributes and text content */ ahref:'http://groovy.codehaus.org' ["Groovy"] } } 32
  • 33. Builders in Kotlin html { head { title { +"XML encoding with Kotlin" } } body { h1 { +"XML encoding with Kotlin" } p { +"this format is now type-safe" } /* an element with attributes and text content */ a(href="http://jetbrains.com/kotlin") { +"Kotlin" } } } 33
  • 34. Builders: Implementation (I) • Function definition fun html(init : fun HTML.() : Unit) : HTML { val html = HTML() html.init() return html } • Usage html { this.head { ... } } 34
  • 35. Builders: Implementation (II) • Function definition fun html(init : fun HTML.() : Unit) : HTML { val html = HTML() html.init() return html } • Usage html { head { ... } } 35
  • 36. Builders: Implementation (III) abstract class Tag(val name : String) : Element { val children = ArrayList<Element>() val attributes = HashMap<String, String>() } abstract class TagWithText(name : String) : Tag(name) { fun String.plus() { children.add(TextElement(this)) } } class HTML() : Tag("html") { fun head(init : fun Head.() : Unit) { } fun body(init : fun Body.() : Unit) { } } 36
  • 37. Builders in Kotlin html { head { title { +"XML encoding with Kotlin" } } body { h1 { +"XML encoding with Kotlin" } p { +"this format is now type-safe" } /* an element with attributes and text content */ a(href="http://jetbrains.com/kotlin") { +"Kotlin" } } } 37
  • 38. Generics: Invariance class List<T> { fun add(t : T) fun get(index : Int) : T } val ints = List<Int>() val anys : List<Any> = ints anys.add("1") // Cause of the problem val i : Int = ints.get(0) // !!! 38
  • 39. Generics: Declaration-site variance class List<T> { List<Int> >:< List<Any> fun add(t : T) val ints = List<Int>() fun get() : T val anys : List<Any> = ints } class Producer<out T> { val ints = Producer<Int>() fun get() : T val anys : Producer<Any> = ints } class Consumer<in T> { val anys = Consumer<Any>() fun add(t : T) val ints : Consumer<Int> = anys } 39
  • 40. Generics: Use-site variance val ints = List<Int>() val anysOut : List<out Any> = ints anysOut.add("1") // Not available val i : Int = ints.get() // No problem val anys = List<Any>() val intsIn : List<in Int> = anys intsIn.add(0) val obj = intsIn.get() // : Any? 40
  • 41. Reified generics • Type information in retained at runtime ➡ foo is List<T> ➡ Array<T>(3) ➡ T.create() • Java types are still erased ➡ foo is java.util.List<*> 41
  • 42. Class objects (I) • Classes have no static members • Each class may have a class object associated to it: class Example() { class object { fun create() = Example() } } val e = Example.create() 42
  • 43. Class objects (II) • Class objects can have supertypes: class Example() { class object : Factory<Example> { override fun create() = Example() } } val factory : Factory<Example> = Example val e : Example = factory.create() 43
  • 44. Class objects (III) • Generic constraints for class objects: class Lazy<T>() where class object T : Factory<T> { private var store : T? = null public val value : T get() { if (store == null) { store = T.create() } return store } } 44
  • 45. Resources • Documentation: ➡ http://jetbrains.com/kotlin • Blog: ➡ http://blog.jetbrains.com/kotlin • Twitter: ➡ @project_kotlin ➡ @abreslav 45