SlideShare a Scribd company logo
1 of 52
Download to read offline
The Kotlin
                Programming Language

                          Andrey Breslav




Monday, October 3, 2011
What is Kotlin?
                    •     Statically typed
                    •     object-oriented
                    •     JVM-targeted
                    •     general-purpose
                    •     programming language
                    •     developed by JetBrains
                          ➡   intended for industrial use



                    •     Docs available today
                    •     Public beta is planned for the end of 2011

                                                            2
Monday, October 3, 2011
Goal-wise...




                               3
Monday, October 3, 2011
Goal-wise...
                    • Number of research papers we are
                          planning to publish on Kotlin is




                                            3
Monday, October 3, 2011
Goal-wise...
                    • Number of research papers we are
                          planning to publish on Kotlin is
                          ➡   Zero




                                            3
Monday, October 3, 2011
Goal-wise...
                    • Number of research papers we are
                          planning to publish on Kotlin is
                          ➡   Zero
                          ➡   ... or really close to that




                                                   3
Monday, October 3, 2011
Outline
                    • Motivation
                    • Feature overview
                    • Basic syntax
                    • Classes and Types
                    • Higher-order functions
                    • Type-safe Groovy-style Builders
                                       4
Monday, October 3, 2011
Motivation




                             5
Monday, October 3, 2011
Motivation
                    •     Why a new language?
                          ➡   We are not satisfied with the existing ones
                          ➡   And we have had a close look at many of them over 10 years




                                                     5
Monday, October 3, 2011
Motivation
                    •     Why a new language?
                          ➡   We are not satisfied with the existing ones
                          ➡   And we have had a close look at many of them over 10 years

                    •     Design goals
                          ➡   Full Java interoperability
                          ➡   Compiles as fast as Java
                          ➡   Safer than Java
                          ➡   More concise than Java
                          ➡   Way simpler than Scala
                                                     5
Monday, October 3, 2011
Feature overview




                             6
Monday, October 3, 2011
Feature overview
                                                                                                               ds)
                                                              s                                           f iel
                                              tee                                                   (no
                                           ran                                             rtie
                                                                                                  s
                                        gua                                              e
                                   ety                                            P   rop
                              - saf T
                          null       rai
                     c                   t   s&
               St ati                             Fir
                                                                                                              Reifie
                                                                                                                     d   gene
                                                        st-                                                                   rics
                                                              cla
                                                                 ss
                                                                      de
                                                                         le   ga
                                                                                tio
                                                                                   n         Declaration-site variance & "Type projections"
   Hig
      her-
           o
                                     Inline-functions (zero-overhead closures)                                                     t ure
                  rder                                                                                                          uc
                       func                                                                                                st r
                            tio     ns (                                                                              infra             Pattern matching
                                        "                                                                           d
                                             clos
                                                    ures                                                         uil
                                                         ")                                               dB
   Extension functions                                                                                s an
                                                                                                ule
                                                                                             Mod
                                                                                         6
Monday, October 3, 2011
Feature overview
                                                                                                       ds)
                                                              s                                   f iel
                                              tee                                           (no
                                           ran                                     rtie
                                                                                          s
                                        gua                                      e
                                   ety                                    P   rop
                              - saf T
                          null       rai
                     c                   t   s&
               St ati                             Fir
                                                                                                      Reifie
                                                                                                             d   gene
                                                        st-                                                           rics
                                                              cla
                                                                 ss
            Full-featured IDE by JetBrains from the very beginning
                                  de
                                     le                               ga
                                                                        tio
                                                                           n         Declaration-site variance & "Type projections"
   Hig
      her-
           o
                                     Inline-functions (zero-overhead closures)                                             t ure
                  rder                                                                                                  uc
                       func                                                                                        st r
                            tio     ns (                                                                      infra             Pattern matching
                                        "                                                                   d
                                             clos
                                                    ures                                                 uil
                                                         ")                                       dB
   Extension functions                                                                        s an
                                                                                        ule
                                                                                     Mod
                                                                                 6
Monday, October 3, 2011
Code examples
                    •     Functions
                    •     Java interoperability
                    •     String templates
                    •     Local variables
                    •     Type inference
                    •     Extension functions and properties
                    •     Null-safety

                                                  7
Monday, October 3, 2011
Hello, world!
                namespace hello

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

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




                                           8
Monday, October 3, 2011
Hello, <names>!
                fun main(args : Array<String>) {
                    var names : String = ""

                          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)




                                                 9
Monday, October 3, 2011
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)
                }



                                                 10
Monday, October 3, 2011
Hello, <names>! (Realistic version)
                fun main(args : Array<String>) {
                    println("Hello, ${args.join(", ")}!")
                }

                fun <T> Iterable<T>.join(separator : String) : String {
                    val names = StringBuilder()
                    forit (this) {
                        names += it.next()
                        if (it.hasNext())
                            names += separator
                    }
                    return names.toString()
                }




                                           11
Monday, October 3, 2011
join() and forit()
                fun <T> Iterable<T>.join(separator : String) : String {
                    val names = StringBuilder()
                    forit (this) {
                        names += it.next()
                        if (it.hasNext())
                            names += separator
                    }
                    return names.toString()
                }


                fun <T> forit(col : Iterable<T>, f : fun(Iterator<T>) : Unit) {
                    val it = col.iterator()
                    while (it.hasNext()) {
                        f(it)
                    }
                }

                                            12
Monday, October 3, 2011
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)
                          }
                }
                                                 13
Monday, October 3, 2011
Types
                                                           Syntax

                                         Class types                    List<Foo>

                                      Nullable types                      Foo?

                                      Function types                fun (Int) : String

                                         Tuple types                (Double, Double)

                                            Self type                     This

                                                        Special types

                                                Top                       Any?

                                            Bottom                       Nothing

                          No meaningful return value                      Unit

                                                             14
Monday, October 3, 2011
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?


                                               15
Monday, October 3, 2011
Automatic 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 => ...
                    }
                }




                                              16
Monday, October 3, 2011
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"
                    }
                }




                                           17
Monday, October 3, 2011
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

                                                  18
Monday, October 3, 2011
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
                }


                                         19
Monday, October 3, 2011
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()
                }



                                                20
Monday, October 3, 2011
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 = super.get()
                }




                                                     21
Monday, October 3, 2011
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()}


                                                   22
Monday, October 3, 2011
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 }


                                                  23
Monday, October 3, 2011
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 }


                                             24
Monday, October 3, 2011
Lock example (I)
                myLock.lock()
                try {
                     // Do something
                }
                finally {
                     myLock.unlock()
                }




                                       25
Monday, October 3, 2011
Lock example (II)

                lock(myLock) {
                     // Do something
                }




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


                                       26
Monday, October 3, 2011
Lock example (III)
                inline fun lock(l : Lock, body : fun () : Unit) {
                     l.lock()
                     try {
                          body()
                     }
                     finally {
                          l.unlock()
                     }
                }


                                       27
Monday, October 3, 2011
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()}



                                               28
Monday, October 3, 2011
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"]
                      }
                }



                                                    29
Monday, October 3, 2011
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" }
                      }
                }



                                                    30
Monday, October 3, 2011
Builders: Implementation (I)
                    •     Function definition

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

                          html {
                            this.head { ... }
                          }


                                                31
Monday, October 3, 2011
Builders: Implementation (II)
                    •     Function definition

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

                          html {
                            head { ... }
                          }


                                                32
Monday, October 3, 2011
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) { }
                }



                                           33
Monday, October 3, 2011
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" }
                      }
                }



                                                    34
Monday, October 3, 2011
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) // !!!
                                         35
Monday, October 3, 2011
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
                }



                                             36
Monday, October 3, 2011
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




                                     37
Monday, October 3, 2011
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?

                                     37
Monday, October 3, 2011
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<*>



                                            38
Monday, October 3, 2011
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()




                                                39
Monday, October 3, 2011
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()




                                            40
Monday, October 3, 2011
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
                              }
                          }



                                             41
Monday, October 3, 2011
We are hiring
                    • Full-time
                          ➡   Back-end development
                          ➡   Standard library development
                          ➡   Static analyses and Refactorings
                          ➡   Incremental compilation

                    • Internships

                                                42
Monday, October 3, 2011
Resources
                    • Documentation:
                          ➡   http://jetbrains.com/kotlin

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

                    • Twitter:
                          ➡   @project_kotlin
                          ➡   @abreslav

                                                  43
Monday, October 3, 2011
Practical Type Systems                                                (seminar)


                    •     Topics
                          ➡   Type systems of industrial languages (e.g. C#, Java, Scala, Kotlin)
                          ➡   Cutting-edge work on OOP and Generic programming
                          ➡   Formalizing Kotlin

                    •     Location
                          ➡   JetBrains, Kantemirovskaya, 2A (m. "Lesnaya")

                    •     Day/Time
                          ➡   TBD

                    •     To participate
                          ➡   andrey.breslav@jetbrains.com


                                                          44
Monday, October 3, 2011

More Related Content

More from Computer Science Club

20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugs20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugsComputer Science Club
 
20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugsComputer Science Club
 
20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugs20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugsComputer Science Club
 
20140511 parallel programming_kalishenko_lecture12
20140511 parallel programming_kalishenko_lecture1220140511 parallel programming_kalishenko_lecture12
20140511 parallel programming_kalishenko_lecture12Computer Science Club
 
20140427 parallel programming_zlobin_lecture11
20140427 parallel programming_zlobin_lecture1120140427 parallel programming_zlobin_lecture11
20140427 parallel programming_zlobin_lecture11Computer Science Club
 
20140420 parallel programming_kalishenko_lecture10
20140420 parallel programming_kalishenko_lecture1020140420 parallel programming_kalishenko_lecture10
20140420 parallel programming_kalishenko_lecture10Computer Science Club
 
20140413 parallel programming_kalishenko_lecture09
20140413 parallel programming_kalishenko_lecture0920140413 parallel programming_kalishenko_lecture09
20140413 parallel programming_kalishenko_lecture09Computer Science Club
 
20140329 graph drawing_dainiak_lecture02
20140329 graph drawing_dainiak_lecture0220140329 graph drawing_dainiak_lecture02
20140329 graph drawing_dainiak_lecture02Computer Science Club
 
20140329 graph drawing_dainiak_lecture01
20140329 graph drawing_dainiak_lecture0120140329 graph drawing_dainiak_lecture01
20140329 graph drawing_dainiak_lecture01Computer Science Club
 
20140310 parallel programming_kalishenko_lecture03-04
20140310 parallel programming_kalishenko_lecture03-0420140310 parallel programming_kalishenko_lecture03-04
20140310 parallel programming_kalishenko_lecture03-04Computer Science Club
 
20140216 parallel programming_kalishenko_lecture01
20140216 parallel programming_kalishenko_lecture0120140216 parallel programming_kalishenko_lecture01
20140216 parallel programming_kalishenko_lecture01Computer Science Club
 

More from Computer Science Club (20)

20141223 kuznetsov distributed
20141223 kuznetsov distributed20141223 kuznetsov distributed
20141223 kuznetsov distributed
 
Computer Vision
Computer VisionComputer Vision
Computer Vision
 
20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugs20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugs
 
20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs
 
20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugs20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugs
 
20140511 parallel programming_kalishenko_lecture12
20140511 parallel programming_kalishenko_lecture1220140511 parallel programming_kalishenko_lecture12
20140511 parallel programming_kalishenko_lecture12
 
20140427 parallel programming_zlobin_lecture11
20140427 parallel programming_zlobin_lecture1120140427 parallel programming_zlobin_lecture11
20140427 parallel programming_zlobin_lecture11
 
20140420 parallel programming_kalishenko_lecture10
20140420 parallel programming_kalishenko_lecture1020140420 parallel programming_kalishenko_lecture10
20140420 parallel programming_kalishenko_lecture10
 
20140413 parallel programming_kalishenko_lecture09
20140413 parallel programming_kalishenko_lecture0920140413 parallel programming_kalishenko_lecture09
20140413 parallel programming_kalishenko_lecture09
 
20140329 graph drawing_dainiak_lecture02
20140329 graph drawing_dainiak_lecture0220140329 graph drawing_dainiak_lecture02
20140329 graph drawing_dainiak_lecture02
 
20140329 graph drawing_dainiak_lecture01
20140329 graph drawing_dainiak_lecture0120140329 graph drawing_dainiak_lecture01
20140329 graph drawing_dainiak_lecture01
 
20140310 parallel programming_kalishenko_lecture03-04
20140310 parallel programming_kalishenko_lecture03-0420140310 parallel programming_kalishenko_lecture03-04
20140310 parallel programming_kalishenko_lecture03-04
 
20140223-SuffixTrees-lecture01-03
20140223-SuffixTrees-lecture01-0320140223-SuffixTrees-lecture01-03
20140223-SuffixTrees-lecture01-03
 
20140216 parallel programming_kalishenko_lecture01
20140216 parallel programming_kalishenko_lecture0120140216 parallel programming_kalishenko_lecture01
20140216 parallel programming_kalishenko_lecture01
 
20131106 h10 lecture6_matiyasevich
20131106 h10 lecture6_matiyasevich20131106 h10 lecture6_matiyasevich
20131106 h10 lecture6_matiyasevich
 
20131027 h10 lecture5_matiyasevich
20131027 h10 lecture5_matiyasevich20131027 h10 lecture5_matiyasevich
20131027 h10 lecture5_matiyasevich
 
20131027 h10 lecture5_matiyasevich
20131027 h10 lecture5_matiyasevich20131027 h10 lecture5_matiyasevich
20131027 h10 lecture5_matiyasevich
 
20131013 h10 lecture4_matiyasevich
20131013 h10 lecture4_matiyasevich20131013 h10 lecture4_matiyasevich
20131013 h10 lecture4_matiyasevich
 
20131006 h10 lecture3_matiyasevich
20131006 h10 lecture3_matiyasevich20131006 h10 lecture3_matiyasevich
20131006 h10 lecture3_matiyasevich
 
20131006 h10 lecture3_matiyasevich
20131006 h10 lecture3_matiyasevich20131006 h10 lecture3_matiyasevich
20131006 h10 lecture3_matiyasevich
 

Recently uploaded

Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 

Recently uploaded (20)

Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 

20111002 csseminar kotlin

  • 1. The Kotlin Programming Language Andrey Breslav Monday, October 3, 2011
  • 2. What is Kotlin? • Statically typed • object-oriented • JVM-targeted • general-purpose • programming language • developed by JetBrains ➡ intended for industrial use • Docs available today • Public beta is planned for the end of 2011 2 Monday, October 3, 2011
  • 3. Goal-wise... 3 Monday, October 3, 2011
  • 4. Goal-wise... • Number of research papers we are planning to publish on Kotlin is 3 Monday, October 3, 2011
  • 5. Goal-wise... • Number of research papers we are planning to publish on Kotlin is ➡ Zero 3 Monday, October 3, 2011
  • 6. Goal-wise... • Number of research papers we are planning to publish on Kotlin is ➡ Zero ➡ ... or really close to that 3 Monday, October 3, 2011
  • 7. Outline • Motivation • Feature overview • Basic syntax • Classes and Types • Higher-order functions • Type-safe Groovy-style Builders 4 Monday, October 3, 2011
  • 8. Motivation 5 Monday, October 3, 2011
  • 9. Motivation • Why a new language? ➡ We are not satisfied with the existing ones ➡ And we have had a close look at many of them over 10 years 5 Monday, October 3, 2011
  • 10. Motivation • Why a new language? ➡ We are not satisfied with the existing ones ➡ And we have had a close look at many of them over 10 years • Design goals ➡ Full Java interoperability ➡ Compiles as fast as Java ➡ Safer than Java ➡ More concise than Java ➡ Way simpler than Scala 5 Monday, October 3, 2011
  • 11. Feature overview 6 Monday, October 3, 2011
  • 12. Feature overview ds) s f iel tee (no ran rtie s gua e ety P rop - saf T null rai c t s& St ati Fir Reifie d gene st- rics cla ss de le ga tio n Declaration-site variance & "Type projections" Hig her- o Inline-functions (zero-overhead closures) t ure rder uc func st r tio ns ( infra Pattern matching " d clos ures uil ") dB Extension functions s an ule Mod 6 Monday, October 3, 2011
  • 13. Feature overview ds) s f iel tee (no ran rtie s gua e ety P rop - saf T null rai c t s& St ati Fir Reifie d gene st- rics cla ss Full-featured IDE by JetBrains from the very beginning de le ga tio n Declaration-site variance & "Type projections" Hig her- o Inline-functions (zero-overhead closures) t ure rder uc func st r tio ns ( infra Pattern matching " d clos ures uil ") dB Extension functions s an ule Mod 6 Monday, October 3, 2011
  • 14. Code examples • Functions • Java interoperability • String templates • Local variables • Type inference • Extension functions and properties • Null-safety 7 Monday, October 3, 2011
  • 15. Hello, world! namespace hello fun main(args : Array<String>) : Unit { println("Hello, world!") } fun println(message : String) { System.out?.println(message) } 8 Monday, October 3, 2011
  • 16. Hello, <names>! fun main(args : Array<String>) { var names : String = "" 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) 9 Monday, October 3, 2011
  • 17. 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) } 10 Monday, October 3, 2011
  • 18. Hello, <names>! (Realistic version) fun main(args : Array<String>) { println("Hello, ${args.join(", ")}!") } fun <T> Iterable<T>.join(separator : String) : String { val names = StringBuilder() forit (this) { names += it.next() if (it.hasNext()) names += separator } return names.toString() } 11 Monday, October 3, 2011
  • 19. join() and forit() fun <T> Iterable<T>.join(separator : String) : String { val names = StringBuilder() forit (this) { names += it.next() if (it.hasNext()) names += separator } return names.toString() } fun <T> forit(col : Iterable<T>, f : fun(Iterator<T>) : Unit) { val it = col.iterator() while (it.hasNext()) { f(it) } } 12 Monday, October 3, 2011
  • 20. 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) } } 13 Monday, October 3, 2011
  • 21. Types Syntax Class types List<Foo> Nullable types Foo? Function types fun (Int) : String Tuple types (Double, Double) Self type This Special types Top Any? Bottom Nothing No meaningful return value Unit 14 Monday, October 3, 2011
  • 22. 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? 15 Monday, October 3, 2011
  • 23. Automatic 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 => ... } } 16 Monday, October 3, 2011
  • 24. 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" } } 17 Monday, October 3, 2011
  • 25. 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 18 Monday, October 3, 2011
  • 26. 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 } 19 Monday, October 3, 2011
  • 27. 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() } 20 Monday, October 3, 2011
  • 28. 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 = super.get() } 21 Monday, October 3, 2011
  • 29. 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()} 22 Monday, October 3, 2011
  • 30. 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 } 23 Monday, October 3, 2011
  • 31. 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 } 24 Monday, October 3, 2011
  • 32. Lock example (I) myLock.lock() try { // Do something } finally { myLock.unlock() } 25 Monday, October 3, 2011
  • 33. Lock example (II) lock(myLock) { // Do something } fun lock(l : Lock, body : fun () : Unit) 26 Monday, October 3, 2011
  • 34. Lock example (III) inline fun lock(l : Lock, body : fun () : Unit) { l.lock() try { body() } finally { l.unlock() } } 27 Monday, October 3, 2011
  • 35. 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()} 28 Monday, October 3, 2011
  • 36. 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"] } } 29 Monday, October 3, 2011
  • 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" } } } 30 Monday, October 3, 2011
  • 38. Builders: Implementation (I) • Function definition fun html(init : fun HTML.() : Unit) : HTML { val html = HTML() html.init() return html } • Usage html { this.head { ... } } 31 Monday, October 3, 2011
  • 39. Builders: Implementation (II) • Function definition fun html(init : fun HTML.() : Unit) : HTML { val html = HTML() html.init() return html } • Usage html { head { ... } } 32 Monday, October 3, 2011
  • 40. 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) { } } 33 Monday, October 3, 2011
  • 41. 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" } } } 34 Monday, October 3, 2011
  • 42. 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) // !!! 35 Monday, October 3, 2011
  • 43. 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 } 36 Monday, October 3, 2011
  • 44. 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 37 Monday, October 3, 2011
  • 45. 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? 37 Monday, October 3, 2011
  • 46. 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<*> 38 Monday, October 3, 2011
  • 47. 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() 39 Monday, October 3, 2011
  • 48. 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() 40 Monday, October 3, 2011
  • 49. 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 } } 41 Monday, October 3, 2011
  • 50. We are hiring • Full-time ➡ Back-end development ➡ Standard library development ➡ Static analyses and Refactorings ➡ Incremental compilation • Internships 42 Monday, October 3, 2011
  • 51. Resources • Documentation: ➡ http://jetbrains.com/kotlin • Blog: ➡ http://blog.jetbrains.com/kotlin • Twitter: ➡ @project_kotlin ➡ @abreslav 43 Monday, October 3, 2011
  • 52. Practical Type Systems (seminar) • Topics ➡ Type systems of industrial languages (e.g. C#, Java, Scala, Kotlin) ➡ Cutting-edge work on OOP and Generic programming ➡ Formalizing Kotlin • Location ➡ JetBrains, Kantemirovskaya, 2A (m. "Lesnaya") • Day/Time ➡ TBD • To participate ➡ andrey.breslav@jetbrains.com 44 Monday, October 3, 2011