SlideShare uma empresa Scribd logo
1 de 72
Baixar para ler offline
THE KOTLIN
         PROGRAMMING LANGUAGE


                             Sergey Lukjanov, 2012
                            slukjanov@mirantis.com
                                      1
Thursday, February 16, 12
WHAT IS KOTLIN?
         •JVM-targeted
         •Statically typed
         •Object-oriented
         •General purpose
         •Programming language
         •Docs available today
         •Open source from Feb 14


                                2
Thursday, February 16, 12
OUTLINE
         •Motivation
         •Design goals
         •Feature overview
         •Basic syntax
         •Classes, types, inheritance
         •High-order functions
         •Generics
         •Tuples
         •Pattern matching
         •Class objects
                                    3
Thursday, February 16, 12
MOTIVATION




                            4
Thursday, February 16, 12
MOTIVATION
         •IDEA codebase ≥ 200MB Java-code, ≥ 50k classes




                                 4
Thursday, February 16, 12
MOTIVATION
         •IDEA codebase ≥ 200MB Java-code, ≥ 50k classes
         •Java libraries and community




                                 4
Thursday, February 16, 12
MOTIVATION
         •IDEA codebase ≥ 200MB Java-code, ≥ 50k classes
         •Java libraries and community
         •There are many languages, why not try?




                                 4
Thursday, February 16, 12
DESIGN GOALS




                            5
Thursday, February 16, 12
DESIGN GOALS
         •Full Java interoperability




                                       5
Thursday, February 16, 12
DESIGN GOALS
         •Full Java interoperability
         •Compiles as fast as Java




                                       5
Thursday, February 16, 12
DESIGN GOALS
         •Full Java interoperability
         •Compiles as fast as Java
         •Safer than Java




                                       5
Thursday, February 16, 12
DESIGN GOALS
         •Full Java interoperability
         •Compiles as fast as Java
         •Safer than Java
         •More concise than Java




                                       5
Thursday, February 16, 12
DESIGN GOALS
         •Full Java interoperability
         •Compiles as fast as Java
         •Safer than Java
         •More concise than Java
         •Way simpler than Scala




                                       5
Thursday, February 16, 12
FEATURE OVERVIEW 1/2
         •Static null-safety guarantees
         •Traits
         •First-class delegation
         •Properties (instead of fields)
         •Reified generics
         •Declaration-site variance & “Type projections”
         •High-order functions (“closures”)
         •Extension properties and functions
         •Inline-functions (zero-overhead closures)
                                   6
Thursday, February 16, 12
FEATURE OVERVIEW 2/2
         •Tuples
         •Modules and build infrastructure
         •Pattern matching
         •Range expressions
         •String templates
         •Singletons
         •Operator overloading
         •Full-featured IDE by JetBrains
         •Java to Kotlin converting
                                   7
Thursday, February 16, 12
CODE EXAMPLES




                            8
Thursday, February 16, 12
HELLO, WORLD!
         fun main(args : Array<String>) : Unit {
             println("Hello, World!");
         }

         fun println(any : Any?) /* : Unit */ {
             System.out?.println(any);
         }




                                       9
Thursday, February 16, 12
HELLO, <NAMES>!
         fun main(args : Array<String>) {
             var names = ""; // names : String

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

                    println("Hello, $names!") // Groovy-style templates
         }

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




                                              10
Thursday, February 16, 12
HELLO, <NAMES>! (FASTER)
         fun main(args : Array<String>) {
             var names = StringBuilder(); // names : StringBuilder

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

                    println("Hello, $names!") // Groovy-style templates
         }

         fun StringBuilder.plusAssign(any : Any?) {
             this.append(any)
         }




                                              11
Thursday, February 16, 12
HELLO, <NAMES>! (REALISTIC)
         fun main(args : Array<String>) {
             println("Hello, ${args.join(", ")}!")
         }




                                       12
Thursday, February 16, 12
HELLO, <NAMES>! (REALISTIC)
         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() ?: ""
         }

         fun <T> forit(col : Iterable<T>, f : (Iterator<T>) -> Unit) {
             val it = col.iterator()
             while (it.hasNext)
                 f(it)
         }
                                              12
Thursday, February 16, 12
NULL-SAFETY 1/2
         fun parseInt(str : String) : Int? {
             try {
                 return Integer.parseInt(str)
             } catch (e : NumberFormatException) {
                 return null
             }
         }




                                       13
Thursday, February 16, 12
NULL-SAFETY 1/2
         fun parseInt(str : String) : Int? {
             try {
                 return Integer.parseInt(str)
             } catch (e : NumberFormatException) {
                 return null
             }
         }

         fun main(args : Array<String>) {
             val x = parseInt("1027")
             val y = parseInt("Hello, World!") // y == null
             println(x?.times(2)) // can’t write x * 2
             println(x?.times(y)) // times argument can't be nullable
             println(x?.times(y.sure())) // throws NPE if y == null
             if (x != null) {
                 println(x * 2)
             }
         }

                                       13
Thursday, February 16, 12
NULL-SAFETY 2/2
         fun String?.isNullOrEmpty() : Boolean {
             return this == null || this.trim().length == 0
         }




                                       14
Thursday, February 16, 12
NULL-SAFETY 2/2
         fun String?.isNullOrEmpty() : Boolean {
             return this == null || this.trim().length == 0
         }


         fun main(args : Array<String>) {
             println("Hello".isNullOrEmpty())     //   false
             println(" World ".isNullOrEmpty())   //   false
             println("    ".isNullOrEmpty())      //   true
             println(null.isNullOrEmpty())        //   true
         }




                                       14
Thursday, February 16, 12
AUTOMATIC CASTS
         fun foo(obj : Any?) {
             if (obj is String) {
                 println(obj.get(0));
             }
         }




                                        15
Thursday, February 16, 12
WHEN STATEMENT
         fun foo(obj : Any?) {
             val x : Any? = when (obj) {
                 is String -> obj.get(0)           // autocast to String
                 is Int -> obj + 1                 // autocast to Int
                 !is Boolean -> null
                 else -> "unknown"
             }

                    val i : Int = when (obj) {
                        is String -> if(obj.startsWith("a")) 1 else 0
                        is Int -> obj
                        else -> -1
                    }
         }




                                              16
Thursday, February 16, 12
TYPES 1/2
                                             Syntax
                             Class types               List<Foo>

                            Nullable types               Foo?

                            Function types          (Int) -> String

                             Tuple types              (Int, Int)

                              Self types                 This



                                               17
Thursday, February 16, 12
TYPES 2/2
                                     Special types

                             Top                      Any?


                            Bottom                   Nothing


              No meaningful return value              Unit



                                           18
Thursday, February 16, 12
TYPES HIERARCHY
                                         Any?

          Int?                String?      ...        Any


                            Nothing?                  Int   Unit


                                        Nothing

             Complete lattice
                                                 19
Thursday, February 16, 12
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?>?
                Array<Int>        int[]        Array<Int>?
                List<Int>     List<Integer> List<Int?>?
                 Nothing             -               -
                    Foo            Foo            Foo?
                                   20
Thursday, February 16, 12
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?>?
                Array<Int>        int[]        Array<Int>?
                List<Int>     List<Integer> List<Int?>?
                 Nothing             -               -
                    Foo            Foo            Foo?
                                   20
Thursday, February 16, 12
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?>?
                Array<Int>        int[]        Array<Int>?
                List<Int>     List<Integer> List<Int?>?
                 Nothing             -               -
                    Foo            Foo            Foo?
                                   20
Thursday, February 16, 12
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?>?
                Array<Int>        int[]        Array<Int>?
                List<Int>     List<Integer> List<Int?>?
                 Nothing             -               -
                    Foo            Foo            Foo?
                                   20
Thursday, February 16, 12
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?>?
                Array<Int>        int[]        Array<Int>?
                List<Int>     List<Integer> List<Int?>?
                 Nothing             -               -
                    Foo            Foo            Foo?
                                   20
Thursday, February 16, 12
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?>?
                Array<Int>        int[]        Array<Int>?
                List<Int>     List<Integer> List<Int?>?
                 Nothing             -               -
                    Foo            Foo            Foo?
                                   20
Thursday, February 16, 12
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?>?
                Array<Int>        int[]        Array<Int>?
                List<Int>     List<Integer> List<Int?>?
                 Nothing             -               -
                    Foo            Foo            Foo?
                                   20
Thursday, February 16, 12
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?>?
                Array<Int>        int[]        Array<Int>?
                List<Int>     List<Integer> List<Int?>?
                 Nothing             -               -
                    Foo            Foo            Foo?
                                   20
Thursday, February 16, 12
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?>?
                Array<Int>        int[]        Array<Int>?
                List<Int>     List<Integer> List<Int?>?
                 Nothing             -               -
                    Foo            Foo            Foo?
                                   20
Thursday, February 16, 12
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?>?
                Array<Int>        int[]        Array<Int>?
                List<Int>     List<Integer> List<Int?>?
                 Nothing             -               -
                    Foo            Foo            Foo?
                                   20
Thursday, February 16, 12
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?>?
                Array<Int>        int[]        Array<Int>?
                List<Int>     List<Integer> List<Int?>?
                 Nothing             -               -
                    Foo            Foo            Foo?
                                   20
Thursday, February 16, 12
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
Thursday, February 16, 12
TRAITS
         trait T1 : Class1, OtherTrait {
             // no state
         }

         class Foo(p : Bar) : Class1(p), T1, T2 {
             // ...
         }

         class Decorator(p : T2) : Class2(), T2 by p {
             // ...
         }




                                       22
Thursday, February 16, 12
DISAMBIGUATION
         trait A {
             fun foo() : Int = 1 // open by default
         }

         open class B() {
             open fun foo() : Int = 2 // not open by default
         }

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




                                       23
Thursday, February 16, 12
FIRST-CLASS FUNCTIONS
         fun foo(arg : String) : Boolean // function


         (p : Int) -> Int // function type
         (Int) -> Int // function type



         (a : Int) -> a + 1 // function literal

         (b) : Int -> b * 2 // function literal

         c -> c.times(2) // function literal




                                         24
Thursday, February 16, 12
HIGH-ORDER FUNS
         fun <T> filter( c : Iterable<T>, f: (T)->Boolean):Iterable<T>

         filter(list, { s -> s.length < 3 })




                                       25
Thursday, February 16, 12
HIGH-ORDER FUNS
         fun <T> filter( c : Iterable<T>, f: (T)->Boolean):Iterable<T>

         filter(list, { s -> s.length < 3 })

         filter(list) { s -> s.length < 3 }




                                       25
Thursday, February 16, 12
HIGH-ORDER FUNS
         fun <T> filter( c : Iterable<T>, f: (T)->Boolean):Iterable<T>

         filter(list, { s -> s.length < 3 })

         filter(list) { s -> s.length < 3 }
         // if only one arg:




                                       25
Thursday, February 16, 12
HIGH-ORDER FUNS
         fun <T> filter( c : Iterable<T>, f: (T)->Boolean):Iterable<T>

         filter(list, { s -> s.length < 3 })

         filter(list) { s -> s.length < 3 }
         // if only one arg:
         filter(list) { it.length < 3 }




                                       25
Thursday, February 16, 12
LOCAL FUNCTIONS
         fun reachable(from : Vertex, to : Vertex) : Boolean {
             val visited = HashSet<Vertex>()

                    fun dfs(current : Vertex) {
                        // here we return from the outer function:
                        if (current == to) return@reachable true

                            // And here - from local function:
                            if (!visited.add(current)) return

                            for (v in current.neighbors)
                                dfs(v)
                    }

                    dfs(from)
                    return false // if dfs() did not return true already
         }



                                                  26
Thursday, February 16, 12
INFIX FUNCTION CALLS
         // regular call:
         a.contains("123")

         // infix call:
         a contains "123"




                             27
Thursday, February 16, 12
INFIX FUNCTION CALLS
         // regular call:
         a.contains("123")

         // infix call:
         a contains "123"


         // “LINQ”
         users
             .filter { it hasPrivilege WRITE }
             .map { it -> it.fullName }
             .orderBy { it.lastName }




                                       27
Thursday, February 16, 12
LOCK EXAMPLE
         myLock.lock()
         try {
             // do something
         } finally {
             myLock.unlock()
         }




                               28
Thursday, February 16, 12
LOCK EXAMPLE
         myLock.lock()         lock(myLock) {
         try {                     // do something
             // do something   }
         } finally {
             myLock.unlock()
         }




                                  28
Thursday, February 16, 12
LOCK EXAMPLE
         myLock.lock()                     lock(myLock) {
         try {                                 // do something
             // do something               }
         } finally {
             myLock.unlock()
         }



                      inline fun <T> lock(l : Lock, body : () -> T) : T {
                          l.lock()
                          try {
                              return body()
                          } finally {
                              l.unlock()
                          }
                      }



                                               28
Thursday, February 16, 12
GENERICS: INVARIANCE
         class List<T> {
             fun add(t : T)
             fun get(idx : Int) : T
         }

         val intList = List<Int>()
         // We should not be able to do it:
         val anyList : List<Any> = intList
         anyList.add("1") // Cause of the problem
         val i : Int = intList.get(0) // !!!




                                       29
Thursday, February 16, 12
DECLARATION-SITE VARIANCE
         class List<T> {              val intList = List<Int>()
             fun add(t : T)           val anyList : List<Any> = intList
             fun get(idx : Int) : T
         }




                                       30
Thursday, February 16, 12
DECLARATION-SITE VARIANCE
         class List<T> {              val intList = List<Int>()
             fun add(t : T)           val anyList : List<Any> = intList
             fun get(idx : Int) : T
         }

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




                                       30
Thursday, February 16, 12
DECLARATION-SITE VARIANCE
         class List<T> {              val intList = List<Int>()
             fun add(t : T)           val anyList : List<Any> = intList
             fun get(idx : Int) : T
         }

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


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




                                       30
Thursday, February 16, 12
USE-SITE VARIANCE
         val intList = List<Int>()
         val anyListOut : List<out Any> = intList
         anyListOut.add("1") // Not available
         val i : Int = intList.get(0) // No problem




         val anyList = List<Any>()
         val intListIn : List<in Int> = anyList
         intListIn.add(123)
         val obj = intListIn.get(0) // : Any?




                                       31
Thursday, February 16, 12
REIFIED GENERICS
         // Type information is retained in runtime
         foo is List<T>
         Array<T>(10)
         T.create()
         T.javaClass




                                       32
Thursday, February 16, 12
REIFIED GENERICS
         // Type information is retained in runtime
         foo is List<T>
         Array<T>(10)
         T.create()
         T.javaClass


         // Java types is still erased...
         foo is java.util.List<*>




                                       32
Thursday, February 16, 12
TUPLES
         class Tuple2<out T1, out T2>(
           val _1 : T1,
           val _2 : T2
         )

         val pair : #(Int, String) = #(1, "")
         // same as 'Tuple2<Int, String>(1, "")'

         when (x) {
           is #(null, *) => throw NullPointerException()
           is #(val a, val b) => print(a, b)
         }

         print("left = ${pair._1}, right = ${pair._2}")

         val point : #(x : Int, y : Int) // labeled tuple
         print("x = ${point.x}, y = ${point.y}")
         val point : #(x : Int, y : Int) = #(y = 10, x = 5)

                                         33
Thursday, February 16, 12
PATTERN MATCHING 1/2
         when (a) {
             is Tree#(*, null) -> print("no right child")
             is Tree#(val l is Tree, val r is Tree) -> print("$l and $r")
             is Tree -> print("just a tree")
             is #(*, val b in 1..100) -> print(b)
             else -> print("unknown")
         }




                                       34
Thursday, February 16, 12
PATTERN MATCHING 1/2
         when (a) {
             is Tree#(*, null) -> print("no right child")
             is Tree#(val l is Tree, val r is Tree) -> print("$l and $r")
             is Tree -> print("just a tree")
             is #(*, val b in 1..100) -> print(b)
             else -> print("unknown")
         }

         class Tree(val left : Tree?, val right : Tree?)




                                       34
Thursday, February 16, 12
PATTERN MATCHING 1/2
         when (a) {
             is Tree#(*, null) -> print("no right child")
             is Tree#(val l is Tree, val r is Tree) -> print("$l and $r")
             is Tree -> print("just a tree")
             is #(*, val b in 1..100) -> print(b)
             else -> print("unknown")
         }

         class Tree(val left : Tree?, val right : Tree?)

         decomposer fun Any?.Tree() : #(Tree?, Tree?)? {
             return if (this is Tree) #(this.left, this.right) else null
         }




                                       34
Thursday, February 16, 12
PATTERN MATCHING 2/2
         when (d) {
             is mmddyy#(02, 16, val a) -> print("Feb 16th of $a"))
         }


         class Date(val timestamp : Long) {
           fun mmddyy() : #(Int, Int, Int)? = #(month, day, year)
         }


         fun Date.mmddyy() : #(Int, Int, Int)? = #(month, day, year)




                                       35
Thursday, February 16, 12
CLASS OBJECTS 1/2
         class Example() {
             class object {
                 fun create() = Example()
             }
         }

         val e = Example.create()




                                       36
Thursday, February 16, 12
CLASS OBJECTS 2/2
         trait Factory<T> {
             fun create() : T
         }

         class Example2() {
             class object : Factory<Example2> {
                 override fun create() = Example2()
             }
         }

         val factory : Factory<Example2> = Example2
         val e2 : Example2 = factory.create()




                                       37
Thursday, February 16, 12
RESOURCES
         Documentation: http://jetbrains.com/kotlin
         Blog: http://blog.jetbrains.com/kotlin




                                   38
Thursday, February 16, 12
THANKS
         This presentation based on slides and speeches of
         Andrey Breslav, author of Kotlin language.




                                   X
Thursday, February 16, 12
Q&A




                             Sergey Lukjanov, 2012
                            slukjanov@mirantis.com
                                      39
Thursday, February 16, 12

Mais conteúdo relacionado

Mais procurados

Intro to scala
Intro to scalaIntro to scala
Intro to scala
Joe Zulli
 
Javascript, Do you speak it!
Javascript, Do you speak it!Javascript, Do you speak it!
Javascript, Do you speak it!
Victor Porof
 
Scala In The Wild
Scala In The WildScala In The Wild
Scala In The Wild
djspiewak
 
Object-Oriented Programming with Perl and Moose
Object-Oriented Programming with Perl and MooseObject-Oriented Programming with Perl and Moose
Object-Oriented Programming with Perl and Moose
Dave Cross
 

Mais procurados (20)

An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
Using Combine, SwiftUI and callAsFunction to build an experimental localizati...
Using Combine, SwiftUI and callAsFunction to build an experimental localizati...Using Combine, SwiftUI and callAsFunction to build an experimental localizati...
Using Combine, SwiftUI and callAsFunction to build an experimental localizati...
 
Paradigmas de programação funcional + objetos no liquidificador com scala
Paradigmas de programação funcional + objetos no liquidificador com scalaParadigmas de programação funcional + objetos no liquidificador com scala
Paradigmas de programação funcional + objetos no liquidificador com scala
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
 
Scala For Java Programmers
Scala For Java ProgrammersScala For Java Programmers
Scala For Java Programmers
 
JavaSE 7
JavaSE 7JavaSE 7
JavaSE 7
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
Java
JavaJava
Java
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
Java for beginners
Java for beginnersJava for beginners
Java for beginners
 
Scala
ScalaScala
Scala
 
Ceylon - the language and its tools
Ceylon - the language and its toolsCeylon - the language and its tools
Ceylon - the language and its tools
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 
Getting the most out of Java [Nordic Coding-2010]
Getting the most out of Java [Nordic Coding-2010]Getting the most out of Java [Nordic Coding-2010]
Getting the most out of Java [Nordic Coding-2010]
 
Javascript, Do you speak it!
Javascript, Do you speak it!Javascript, Do you speak it!
Javascript, Do you speak it!
 
Scala In The Wild
Scala In The WildScala In The Wild
Scala In The Wild
 
Scale up your thinking
Scale up your thinkingScale up your thinking
Scale up your thinking
 
Object-Oriented Programming with Perl and Moose
Object-Oriented Programming with Perl and MooseObject-Oriented Programming with Perl and Moose
Object-Oriented Programming with Perl and Moose
 
Elementary Sort
Elementary SortElementary Sort
Elementary Sort
 

Semelhante a Kotlin techtalk

BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 

Semelhante a Kotlin techtalk (20)

Effective Scala @ Jfokus
Effective Scala @ JfokusEffective Scala @ Jfokus
Effective Scala @ Jfokus
 
OSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
OSDC.fr 2012 :: Cascalog : progammation logique pour HadoopOSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
OSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
 
Scala for the doubters
Scala for the doubtersScala for the doubters
Scala for the doubters
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
Kotlin: maybe it's the right time
Kotlin: maybe it's the right timeKotlin: maybe it's the right time
Kotlin: maybe it's the right time
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
 
Discover Dart(lang) - Meetup 07/12/2016
Discover Dart(lang) - Meetup 07/12/2016Discover Dart(lang) - Meetup 07/12/2016
Discover Dart(lang) - Meetup 07/12/2016
 
Discover Dart - Meetup 15/02/2017
Discover Dart - Meetup 15/02/2017Discover Dart - Meetup 15/02/2017
Discover Dart - Meetup 15/02/2017
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Scala 101-bcndevcon
Scala 101-bcndevconScala 101-bcndevcon
Scala 101-bcndevcon
 
A brief introduction to dart
A brief introduction to dartA brief introduction to dart
A brief introduction to dart
 
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?
 
Scala on Android
Scala on AndroidScala on Android
Scala on Android
 
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017 Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
 

Mais de Sergey Lukjanov

Atlanta OpenStack Summit: Technical Deep Dive: Big Data Computations Using El...
Atlanta OpenStack Summit: Technical Deep Dive: Big Data Computations Using El...Atlanta OpenStack Summit: Technical Deep Dive: Big Data Computations Using El...
Atlanta OpenStack Summit: Technical Deep Dive: Big Data Computations Using El...
Sergey Lukjanov
 
Atlanta OpenStack Summit: The State of OpenStack Data Processing: Sahara, Now...
Atlanta OpenStack Summit: The State of OpenStack Data Processing: Sahara, Now...Atlanta OpenStack Summit: The State of OpenStack Data Processing: Sahara, Now...
Atlanta OpenStack Summit: The State of OpenStack Data Processing: Sahara, Now...
Sergey Lukjanov
 
Savanna project update Jan 2014
Savanna project update Jan 2014Savanna project update Jan 2014
Savanna project update Jan 2014
Sergey Lukjanov
 
Hong Kong OpenStack Summit: Savanna - Hadoop on OpenStack
Hong Kong OpenStack Summit: Savanna - Hadoop on OpenStackHong Kong OpenStack Summit: Savanna - Hadoop on OpenStack
Hong Kong OpenStack Summit: Savanna - Hadoop on OpenStack
Sergey Lukjanov
 

Mais de Sergey Lukjanov (11)

[Mirantis Day 2015] Проект Sahara - BigData на OpenStack
[Mirantis Day 2015] Проект Sahara - BigData на OpenStack[Mirantis Day 2015] Проект Sahara - BigData на OpenStack
[Mirantis Day 2015] Проект Sahara - BigData на OpenStack
 
OpenStack Data Processing ("Sahara") project update - December 2014
OpenStack Data Processing ("Sahara") project update - December 2014OpenStack Data Processing ("Sahara") project update - December 2014
OpenStack Data Processing ("Sahara") project update - December 2014
 
Atlanta OpenStack Summit: Technical Deep Dive: Big Data Computations Using El...
Atlanta OpenStack Summit: Technical Deep Dive: Big Data Computations Using El...Atlanta OpenStack Summit: Technical Deep Dive: Big Data Computations Using El...
Atlanta OpenStack Summit: Technical Deep Dive: Big Data Computations Using El...
 
Atlanta OpenStack Summit: The State of OpenStack Data Processing: Sahara, Now...
Atlanta OpenStack Summit: The State of OpenStack Data Processing: Sahara, Now...Atlanta OpenStack Summit: The State of OpenStack Data Processing: Sahara, Now...
Atlanta OpenStack Summit: The State of OpenStack Data Processing: Sahara, Now...
 
Savanna project update Jan 2014
Savanna project update Jan 2014Savanna project update Jan 2014
Savanna project update Jan 2014
 
Hong Kong OpenStack Summit: Savanna - Hadoop on OpenStack
Hong Kong OpenStack Summit: Savanna - Hadoop on OpenStackHong Kong OpenStack Summit: Savanna - Hadoop on OpenStack
Hong Kong OpenStack Summit: Savanna - Hadoop on OpenStack
 
Savanna - Elastic Hadoop on OpenStack
Savanna - Elastic Hadoop on OpenStackSavanna - Elastic Hadoop on OpenStack
Savanna - Elastic Hadoop on OpenStack
 
Courses: concurrency #2
Courses: concurrency #2Courses: concurrency #2
Courses: concurrency #2
 
Twitter Storm
Twitter StormTwitter Storm
Twitter Storm
 
Java Agents and Instrumentation techtalk
Java Agents and Instrumentation techtalkJava Agents and Instrumentation techtalk
Java Agents and Instrumentation techtalk
 
Java Bytecode techtalk
Java Bytecode techtalkJava Bytecode techtalk
Java Bytecode techtalk
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 

Kotlin techtalk

  • 1. THE KOTLIN PROGRAMMING LANGUAGE Sergey Lukjanov, 2012 slukjanov@mirantis.com 1 Thursday, February 16, 12
  • 2. WHAT IS KOTLIN? •JVM-targeted •Statically typed •Object-oriented •General purpose •Programming language •Docs available today •Open source from Feb 14 2 Thursday, February 16, 12
  • 3. OUTLINE •Motivation •Design goals •Feature overview •Basic syntax •Classes, types, inheritance •High-order functions •Generics •Tuples •Pattern matching •Class objects 3 Thursday, February 16, 12
  • 4. MOTIVATION 4 Thursday, February 16, 12
  • 5. MOTIVATION •IDEA codebase ≥ 200MB Java-code, ≥ 50k classes 4 Thursday, February 16, 12
  • 6. MOTIVATION •IDEA codebase ≥ 200MB Java-code, ≥ 50k classes •Java libraries and community 4 Thursday, February 16, 12
  • 7. MOTIVATION •IDEA codebase ≥ 200MB Java-code, ≥ 50k classes •Java libraries and community •There are many languages, why not try? 4 Thursday, February 16, 12
  • 8. DESIGN GOALS 5 Thursday, February 16, 12
  • 9. DESIGN GOALS •Full Java interoperability 5 Thursday, February 16, 12
  • 10. DESIGN GOALS •Full Java interoperability •Compiles as fast as Java 5 Thursday, February 16, 12
  • 11. DESIGN GOALS •Full Java interoperability •Compiles as fast as Java •Safer than Java 5 Thursday, February 16, 12
  • 12. DESIGN GOALS •Full Java interoperability •Compiles as fast as Java •Safer than Java •More concise than Java 5 Thursday, February 16, 12
  • 13. DESIGN GOALS •Full Java interoperability •Compiles as fast as Java •Safer than Java •More concise than Java •Way simpler than Scala 5 Thursday, February 16, 12
  • 14. FEATURE OVERVIEW 1/2 •Static null-safety guarantees •Traits •First-class delegation •Properties (instead of fields) •Reified generics •Declaration-site variance & “Type projections” •High-order functions (“closures”) •Extension properties and functions •Inline-functions (zero-overhead closures) 6 Thursday, February 16, 12
  • 15. FEATURE OVERVIEW 2/2 •Tuples •Modules and build infrastructure •Pattern matching •Range expressions •String templates •Singletons •Operator overloading •Full-featured IDE by JetBrains •Java to Kotlin converting 7 Thursday, February 16, 12
  • 16. CODE EXAMPLES 8 Thursday, February 16, 12
  • 17. HELLO, WORLD! fun main(args : Array<String>) : Unit { println("Hello, World!"); } fun println(any : Any?) /* : Unit */ { System.out?.println(any); } 9 Thursday, February 16, 12
  • 18. HELLO, <NAMES>! fun main(args : Array<String>) { var names = ""; // names : String for(idx in args.indices) { names += args[idx] if(idx + 1 < args.size) { names += ", " } } println("Hello, $names!") // Groovy-style templates } val Array<*>.indices : Iterable<Int> get() = IntRange(0, size - 1) 10 Thursday, February 16, 12
  • 19. HELLO, <NAMES>! (FASTER) fun main(args : Array<String>) { var names = StringBuilder(); // names : StringBuilder for(idx in args.indices) { names += args[idx] if(idx + 1 < args.size) { names += ", " } } println("Hello, $names!") // Groovy-style templates } fun StringBuilder.plusAssign(any : Any?) { this.append(any) } 11 Thursday, February 16, 12
  • 20. HELLO, <NAMES>! (REALISTIC) fun main(args : Array<String>) { println("Hello, ${args.join(", ")}!") } 12 Thursday, February 16, 12
  • 21. HELLO, <NAMES>! (REALISTIC) 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() ?: "" } fun <T> forit(col : Iterable<T>, f : (Iterator<T>) -> Unit) { val it = col.iterator() while (it.hasNext) f(it) } 12 Thursday, February 16, 12
  • 22. NULL-SAFETY 1/2 fun parseInt(str : String) : Int? { try { return Integer.parseInt(str) } catch (e : NumberFormatException) { return null } } 13 Thursday, February 16, 12
  • 23. NULL-SAFETY 1/2 fun parseInt(str : String) : Int? { try { return Integer.parseInt(str) } catch (e : NumberFormatException) { return null } } fun main(args : Array<String>) { val x = parseInt("1027") val y = parseInt("Hello, World!") // y == null println(x?.times(2)) // can’t write x * 2 println(x?.times(y)) // times argument can't be nullable println(x?.times(y.sure())) // throws NPE if y == null if (x != null) { println(x * 2) } } 13 Thursday, February 16, 12
  • 24. NULL-SAFETY 2/2 fun String?.isNullOrEmpty() : Boolean { return this == null || this.trim().length == 0 } 14 Thursday, February 16, 12
  • 25. NULL-SAFETY 2/2 fun String?.isNullOrEmpty() : Boolean { return this == null || this.trim().length == 0 } fun main(args : Array<String>) { println("Hello".isNullOrEmpty()) // false println(" World ".isNullOrEmpty()) // false println(" ".isNullOrEmpty()) // true println(null.isNullOrEmpty()) // true } 14 Thursday, February 16, 12
  • 26. AUTOMATIC CASTS fun foo(obj : Any?) { if (obj is String) { println(obj.get(0)); } } 15 Thursday, February 16, 12
  • 27. WHEN STATEMENT fun foo(obj : Any?) { val x : Any? = when (obj) { is String -> obj.get(0) // autocast to String is Int -> obj + 1 // autocast to Int !is Boolean -> null else -> "unknown" } val i : Int = when (obj) { is String -> if(obj.startsWith("a")) 1 else 0 is Int -> obj else -> -1 } } 16 Thursday, February 16, 12
  • 28. TYPES 1/2 Syntax Class types List<Foo> Nullable types Foo? Function types (Int) -> String Tuple types (Int, Int) Self types This 17 Thursday, February 16, 12
  • 29. TYPES 2/2 Special types Top Any? Bottom Nothing No meaningful return value Unit 18 Thursday, February 16, 12
  • 30. TYPES HIERARCHY Any? Int? String? ... Any Nothing? Int Unit Nothing Complete lattice 19 Thursday, February 16, 12
  • 31. 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?>? Array<Int> int[] Array<Int>? List<Int> List<Integer> List<Int?>? Nothing - - Foo Foo Foo? 20 Thursday, February 16, 12
  • 32. 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?>? Array<Int> int[] Array<Int>? List<Int> List<Integer> List<Int?>? Nothing - - Foo Foo Foo? 20 Thursday, February 16, 12
  • 33. 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?>? Array<Int> int[] Array<Int>? List<Int> List<Integer> List<Int?>? Nothing - - Foo Foo Foo? 20 Thursday, February 16, 12
  • 34. 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?>? Array<Int> int[] Array<Int>? List<Int> List<Integer> List<Int?>? Nothing - - Foo Foo Foo? 20 Thursday, February 16, 12
  • 35. 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?>? Array<Int> int[] Array<Int>? List<Int> List<Integer> List<Int?>? Nothing - - Foo Foo Foo? 20 Thursday, February 16, 12
  • 36. 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?>? Array<Int> int[] Array<Int>? List<Int> List<Integer> List<Int?>? Nothing - - Foo Foo Foo? 20 Thursday, February 16, 12
  • 37. 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?>? Array<Int> int[] Array<Int>? List<Int> List<Integer> List<Int?>? Nothing - - Foo Foo Foo? 20 Thursday, February 16, 12
  • 38. 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?>? Array<Int> int[] Array<Int>? List<Int> List<Integer> List<Int?>? Nothing - - Foo Foo Foo? 20 Thursday, February 16, 12
  • 39. 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?>? Array<Int> int[] Array<Int>? List<Int> List<Integer> List<Int?>? Nothing - - Foo Foo Foo? 20 Thursday, February 16, 12
  • 40. 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?>? Array<Int> int[] Array<Int>? List<Int> List<Integer> List<Int?>? Nothing - - Foo Foo Foo? 20 Thursday, February 16, 12
  • 41. 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?>? Array<Int> int[] Array<Int>? List<Int> List<Integer> List<Int?>? Nothing - - Foo Foo Foo? 20 Thursday, February 16, 12
  • 42. 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 Thursday, February 16, 12
  • 43. TRAITS trait T1 : Class1, OtherTrait { // no state } class Foo(p : Bar) : Class1(p), T1, T2 { // ... } class Decorator(p : T2) : Class2(), T2 by p { // ... } 22 Thursday, February 16, 12
  • 44. DISAMBIGUATION trait A { fun foo() : Int = 1 // open by default } open class B() { open fun foo() : Int = 2 // not open by default } class C() : B(), A { override fun foo() = super<A>.foo() // returns 1 } 23 Thursday, February 16, 12
  • 45. FIRST-CLASS FUNCTIONS fun foo(arg : String) : Boolean // function (p : Int) -> Int // function type (Int) -> Int // function type (a : Int) -> a + 1 // function literal (b) : Int -> b * 2 // function literal c -> c.times(2) // function literal 24 Thursday, February 16, 12
  • 46. HIGH-ORDER FUNS fun <T> filter( c : Iterable<T>, f: (T)->Boolean):Iterable<T> filter(list, { s -> s.length < 3 }) 25 Thursday, February 16, 12
  • 47. HIGH-ORDER FUNS fun <T> filter( c : Iterable<T>, f: (T)->Boolean):Iterable<T> filter(list, { s -> s.length < 3 }) filter(list) { s -> s.length < 3 } 25 Thursday, February 16, 12
  • 48. HIGH-ORDER FUNS fun <T> filter( c : Iterable<T>, f: (T)->Boolean):Iterable<T> filter(list, { s -> s.length < 3 }) filter(list) { s -> s.length < 3 } // if only one arg: 25 Thursday, February 16, 12
  • 49. HIGH-ORDER FUNS fun <T> filter( c : Iterable<T>, f: (T)->Boolean):Iterable<T> filter(list, { s -> s.length < 3 }) filter(list) { s -> s.length < 3 } // if only one arg: filter(list) { it.length < 3 } 25 Thursday, February 16, 12
  • 50. LOCAL FUNCTIONS fun reachable(from : Vertex, to : Vertex) : Boolean { val visited = HashSet<Vertex>() fun dfs(current : Vertex) { // here we return from the outer function: if (current == to) return@reachable true // And here - from local function: if (!visited.add(current)) return for (v in current.neighbors) dfs(v) } dfs(from) return false // if dfs() did not return true already } 26 Thursday, February 16, 12
  • 51. INFIX FUNCTION CALLS // regular call: a.contains("123") // infix call: a contains "123" 27 Thursday, February 16, 12
  • 52. INFIX FUNCTION CALLS // regular call: a.contains("123") // infix call: a contains "123" // “LINQ” users .filter { it hasPrivilege WRITE } .map { it -> it.fullName } .orderBy { it.lastName } 27 Thursday, February 16, 12
  • 53. LOCK EXAMPLE myLock.lock() try { // do something } finally { myLock.unlock() } 28 Thursday, February 16, 12
  • 54. LOCK EXAMPLE myLock.lock() lock(myLock) { try { // do something // do something } } finally { myLock.unlock() } 28 Thursday, February 16, 12
  • 55. LOCK EXAMPLE myLock.lock() lock(myLock) { try { // do something // do something } } finally { myLock.unlock() } inline fun <T> lock(l : Lock, body : () -> T) : T { l.lock() try { return body() } finally { l.unlock() } } 28 Thursday, February 16, 12
  • 56. GENERICS: INVARIANCE class List<T> { fun add(t : T) fun get(idx : Int) : T } val intList = List<Int>() // We should not be able to do it: val anyList : List<Any> = intList anyList.add("1") // Cause of the problem val i : Int = intList.get(0) // !!! 29 Thursday, February 16, 12
  • 57. DECLARATION-SITE VARIANCE class List<T> { val intList = List<Int>() fun add(t : T) val anyList : List<Any> = intList fun get(idx : Int) : T } 30 Thursday, February 16, 12
  • 58. DECLARATION-SITE VARIANCE class List<T> { val intList = List<Int>() fun add(t : T) val anyList : List<Any> = intList fun get(idx : Int) : T } class Producer<out T> { val intProd = Producer<Int>() fun get() : T val anyProd : Producer<Any> = intProd } 30 Thursday, February 16, 12
  • 59. DECLARATION-SITE VARIANCE class List<T> { val intList = List<Int>() fun add(t : T) val anyList : List<Any> = intList fun get(idx : Int) : T } class Producer<out T> { val intProd = Producer<Int>() fun get() : T val anyProd : Producer<Any> = intProd } class Consumer<in T> { val anyCons = Consumer<Any>() fun add(t : T) val intCons : Consumer<Int> = anyCons } 30 Thursday, February 16, 12
  • 60. USE-SITE VARIANCE val intList = List<Int>() val anyListOut : List<out Any> = intList anyListOut.add("1") // Not available val i : Int = intList.get(0) // No problem val anyList = List<Any>() val intListIn : List<in Int> = anyList intListIn.add(123) val obj = intListIn.get(0) // : Any? 31 Thursday, February 16, 12
  • 61. REIFIED GENERICS // Type information is retained in runtime foo is List<T> Array<T>(10) T.create() T.javaClass 32 Thursday, February 16, 12
  • 62. REIFIED GENERICS // Type information is retained in runtime foo is List<T> Array<T>(10) T.create() T.javaClass // Java types is still erased... foo is java.util.List<*> 32 Thursday, February 16, 12
  • 63. TUPLES class Tuple2<out T1, out T2>( val _1 : T1, val _2 : T2 ) val pair : #(Int, String) = #(1, "") // same as 'Tuple2<Int, String>(1, "")' when (x) { is #(null, *) => throw NullPointerException() is #(val a, val b) => print(a, b) } print("left = ${pair._1}, right = ${pair._2}") val point : #(x : Int, y : Int) // labeled tuple print("x = ${point.x}, y = ${point.y}") val point : #(x : Int, y : Int) = #(y = 10, x = 5) 33 Thursday, February 16, 12
  • 64. PATTERN MATCHING 1/2 when (a) { is Tree#(*, null) -> print("no right child") is Tree#(val l is Tree, val r is Tree) -> print("$l and $r") is Tree -> print("just a tree") is #(*, val b in 1..100) -> print(b) else -> print("unknown") } 34 Thursday, February 16, 12
  • 65. PATTERN MATCHING 1/2 when (a) { is Tree#(*, null) -> print("no right child") is Tree#(val l is Tree, val r is Tree) -> print("$l and $r") is Tree -> print("just a tree") is #(*, val b in 1..100) -> print(b) else -> print("unknown") } class Tree(val left : Tree?, val right : Tree?) 34 Thursday, February 16, 12
  • 66. PATTERN MATCHING 1/2 when (a) { is Tree#(*, null) -> print("no right child") is Tree#(val l is Tree, val r is Tree) -> print("$l and $r") is Tree -> print("just a tree") is #(*, val b in 1..100) -> print(b) else -> print("unknown") } class Tree(val left : Tree?, val right : Tree?) decomposer fun Any?.Tree() : #(Tree?, Tree?)? { return if (this is Tree) #(this.left, this.right) else null } 34 Thursday, February 16, 12
  • 67. PATTERN MATCHING 2/2 when (d) { is mmddyy#(02, 16, val a) -> print("Feb 16th of $a")) } class Date(val timestamp : Long) { fun mmddyy() : #(Int, Int, Int)? = #(month, day, year) } fun Date.mmddyy() : #(Int, Int, Int)? = #(month, day, year) 35 Thursday, February 16, 12
  • 68. CLASS OBJECTS 1/2 class Example() { class object { fun create() = Example() } } val e = Example.create() 36 Thursday, February 16, 12
  • 69. CLASS OBJECTS 2/2 trait Factory<T> { fun create() : T } class Example2() { class object : Factory<Example2> { override fun create() = Example2() } } val factory : Factory<Example2> = Example2 val e2 : Example2 = factory.create() 37 Thursday, February 16, 12
  • 70. RESOURCES Documentation: http://jetbrains.com/kotlin Blog: http://blog.jetbrains.com/kotlin 38 Thursday, February 16, 12
  • 71. THANKS This presentation based on slides and speeches of Andrey Breslav, author of Kotlin language. X Thursday, February 16, 12
  • 72. Q&A Sergey Lukjanov, 2012 slukjanov@mirantis.com 39 Thursday, February 16, 12