Generating Kotlin Code

A presentation at KotlinConf in November 2017 in San Francisco, CA, USA by Jake Wharton

Slide 1

Slide 1

Kotlin Code Generation Alec Strong & Jake Wharton

Slide 2

Slide 2

public final class User {

private final String firstName ; private final String lastName ; private final int age ; public User (String firstName , String lastName , int age) {

this . firstName = firstName ; this . lastName = lastName ; this . age = age ;

}

public String getFirstName () {

return firstName ;

}

public String getLastName () {

return lastName ;

}

public int getAge () {

return age ;

}

@Override public boolean equals (Object o) {

if ( this == o) return true; if (o == null || getClass() != o.getClass()) return false;

User user = (User) o ; return age == user. age

&& Objects. equals ( firstName , user. firstName ) && Objects. equals ( lastName , user. lastName ) ;

}

@Override public int hashCode () {

return Objects. hash ( firstName , lastName , age ) ;

}

@Override public String toString () {

return "User{"

"firstName='"

firstName

' ' '

", lastName='"

lastName

' ' '

", age="

age

'}' ;

} } data class User(

val firstName : String , val lastName : String , val age : Int )

Slide 3

Slide 3

Bytecode

Slide 4

Slide 4

Protocol Buffers

Slide 5

Slide 5

Protocol Buffers SQL

Slide 6

Slide 6

Protocol Buffers SQL Swagger

Slide 7

Slide 7

Protocol Buffers SQL Swagger Android XML

Slide 8

Slide 8

Protocol Buffers SQL Swagger Android XML YAML

Slide 9

Slide 9

Protocol Buffers SQL Swagger Android XML YAML Mirrors/Elements

Slide 10

Slide 10

SQL Swagger Android XML YAML Mirrors/Elements PSI

Slide 11

Slide 11

Swagger Android XML YAML Mirrors/Elements PSI UAST

Slide 12

Slide 12

Android XML YAML Mirrors/Elements PSI UAST

???

Slide 13

Slide 13

Protocol Buffers SQL Swagger Android XML YAML Mirrors/Elements PSI UAST
???

Slide 14

Slide 14

Protocol Buffers

Slide 15

Slide 15

syntax = "proto2" ; package com.sample; message Ogre {

required string name = 1 ;

repeated int32 layers = 2 ;

optional string swamp = 3 ; }

Slide 16

Slide 16

public final String name ; public final List<Integer> layers ;

public final String swamp ; public Ogre (String name , List<Integer> layers , String swamp) {

this (name , layers , swamp , ByteString. EMPTY ) ; } public Ogre (String name , List<Integer> layers , String swamp ,

ByteString unknownFields) {

super ( ADAPTER , unknownFields) ; this . name = name ; this . layers = Internal. immutableCopyOf ( "layers" , layers) ; this . swamp = swamp ; }

Slide 17

Slide 17

public final String name ; public final List<Integer> layers ;

public final String swamp ; public Ogre (String name , List<Integer> layers , String swamp) {

this (name , layers , swamp , ByteString. EMPTY ) ; } public Ogre (String name , List<Integer> layers , String swamp ,

ByteString unknownFields) {

super ( ADAPTER , unknownFields) ; this . name = name ; this . layers = Internal. immutableCopyOf ( "layers" , layers) ; this . swamp = swamp ; } public final String name ; public final List<Integer> layers ;

public final String swamp ; this . name = name ; this . layers = Internal. immutableCopyOf ( "layers" , layers) ; this . swamp = swamp ;

Slide 18

Slide 18

public final String name ; public final List<Integer> layers ;

public final String swamp ; public Ogre (String name , List<Integer> layers , String swamp) {

this (name , layers , swamp , ByteString. EMPTY ) ; } public Ogre (String name , List<Integer> layers , String swamp ,

ByteString unknownFields) {

super ( ADAPTER , unknownFields) ; this . name = name ; this . layers = Internal. immutableCopyOf ( "layers" , layers) ; this . swamp = swamp ; }

ByteString. EMPTY

ByteString unknownFields

Slide 19

Slide 19

public final String name ; public final List<Integer> layers ;

public final String swamp ; public Ogre (String name , List<Integer> layers , String swamp) {

this (name , layers , swamp , ByteString. EMPTY ) ; } public Ogre (String name , List<Integer> layers , String swamp ,

ByteString unknownFields) {

super ( ADAPTER , unknownFields) ; this . name = name ; this . layers = Internal. immutableCopyOf ( "layers" , layers) ; this . swamp = swamp ; }

Internal. immutableCopyOf ( "layers" , layers)

Slide 20

Slide 20

public final String name ; public final List<Integer> layers ;

public final String swamp ; public Ogre (String name , List<Integer> layers , String swamp) {

this (name , layers , swamp , ByteString. EMPTY ) ; } public Ogre (String name , List<Integer> layers , String swamp ,

ByteString unknownFields) {

super ( ADAPTER , unknownFields) ; this . name = name ; this . layers = Internal. immutableCopyOf ( "layers" , layers) ; this . swamp = swamp ; }

String name

String swamp

String name

String swamp

String name

String swamp

Slide 21

Slide 21

public final String name ; public final List<Integer> layers ;

public final String swamp ; public Ogre (String name , List<Integer> layers , String swamp) {

this (name , layers , swamp , ByteString. EMPTY ) ; } public Ogre (String name , List<Integer> layers , String swamp ,

ByteString unknownFields) {

super ( ADAPTER , unknownFields) ; this . name = name ; this . layers = Internal. immutableCopyOf ( "layers" , layers) ; this . swamp = swamp ; }

Slide 22

Slide 22

class Ogre @JvmOverloads constructor (

val name : String , val layers : List<Int> , val swamp : String? ,

unknownFields: ByteString = ByteString. EMPTY ) : Message<Ogre , Ogre.Builder>( ADAPTER , unknownFields)

Slide 23

Slide 23

class Ogre @JvmOverloads constructor (

val name : String , val layers : List<Int> , val swamp : String? ,

unknownFields: ByteString = ByteString. EMPTY ) : Message<Ogre , Ogre.Builder>( ADAPTER , unknownFields)

val name : String , val layers : List<Int> , val swamp : String? , Ogre shrek = new Ogre( "Shrek" , Arrays. asList ( 1 , 2 ) , null ) ;

System. out .println(shrek.getSwamp()) ;

               s

Slide 24

Slide 24

class Ogre @JvmOverloads constructor (

@JvmField val name : String , @JvmField val layers : List<Int> , @JvmField val swamp : String? ,

unknownFields: ByteString = ByteString. EMPTY ) : Message<Ogre , Ogre.Builder>( ADAPTER , unknownFields)

@JvmField val name : String , @JvmField val layers : List<Int> , @JvmField val swamp : String? , Ogre shrek = new Ogre( "Shrek" , Arrays. asList ( 1 , 2 ) , null ) ;

System. out .println(shrek. swamp ) ;

S e

Slide 25

Slide 25

override fun equals (other: Any?): Boolean {

if (other === this ) return true if (other !is OgreKt) return false val o = other as OgreKt?

return (unknownFields() == o!!.unknownFields() && name == o. name

&& layers == o. layers

&& Internal.equals( swamp , o. swamp )) } override fun hashCode (): Int {

var result = super . hashCode

if (result == 0 ) { result = unknownFields().hashCode() result = result * 37 + name .hashCode() result = result * 37 + layers .hashCode() result = result * 37

  • ( swamp ?.hashCode() ?: 0 )

super . hashCode = result }

return result } override fun toString (): String {

val builder = StringBuilder() builder.append( ", name=" ).append( name )

if (! layers .isEmpty()) builder.append( ", layers=" ).append( layers )

if ( swamp != null ) builder.append( ", swamp=" ).append( swamp )

return builder.replace( 0 , 2 , "Ogre{" ).append( '}' ).toString() }

Slide 26

Slide 26

class Ogre @JvmOverloads constructor (

@JvmField val name : String , @JvmField val layers : List<Int> , @JvmField val swamp : String? ,

unknownFields: ByteString = ByteString. EMPTY ) : Message<Ogre , Ogre.Builder>( ADAPTER , unknownFields)

Slide 27

Slide 27

data class Ogre @JvmOverloads constructor (

@JvmField val name : String , @JvmField val layers : List<Int> , @JvmField val swamp : String? ,

unknownFields: ByteString = ByteString. EMPTY ) : Message<Ogre , Ogre.Builder>( ADAPTER , unknownFields)

Slide 28

Slide 28

data class Ogre @JvmOverloads constructor (

@JvmField val name : String , @JvmField val layers : List<Int> , @JvmField val swamp : String? ,

unknownFields: ByteString = ByteString. EMPTY ) : Message<Ogre , Ogre.Builder>( ADAPTER , unknownFields) data class Ogre

unknownFields: ByteString = ByteString.EMPTY

Slide 29

Slide 29

data class Ogre @JvmOverloads constructor (

@JvmField val name : String , @JvmField val layers : List<Int> , @JvmField val swamp : String? , private val unknownFields: ByteString = ByteString. EMPTY ) : Message<Ogre , Ogre.Builder>( ADAPTER , unknownFields) data class Ogre

private val 

unknownFields : ByteString = ByteString. EMPTY

Slide 30

Slide 30

class Ogre @JvmOverloads constructor (

@JvmField val name : String , @JvmField val layers : List<Int> , @JvmField val swamp : String? ,

unknownFields: ByteString = ByteString. EMPTY ) : Message<Ogre , Ogre.Builder>( ADAPTER , unknownFields)

Slide 31

Slide 31

public static final class Builder extends Message.Builder<Ogre , Builder> {

public String name ; public List<Integer> layers ; public String swamp ; public Builder () {

layers = Internal. newMutableList () ;

}

public Builder name (String name) {

this . name = name ; return this;

}

public Builder layers (List<Integer> layers) { Internal. checkElementsNotNull (layers) ; this . layers = layers ; return this;

}

public Builder swamp (String swamp) {

this . swamp = swamp ; return this;

}

@Override public

Ogre build () {

if ( name

null ) {

throw Internal. missingRequiredFields ( name , "name" ) ;

}

return new Ogre( name , layers , swamp , super .buildUnknownFields()) ;

} }

Slide 32

Slide 32

public static final class Builder extends Message.Builder<Ogre , Builder> {

public String name ; public List<Integer> layers ; public String swamp ; public Builder () {

layers = Internal. newMutableList () ;

}

public Builder name (String name) {

this . name = name ; return this;

}

public Builder layers (List<Integer> layers) { Internal. checkElementsNotNull (layers) ; this . layers = layers ; return this;

}

public Builder swamp (String swamp) {

this . swamp = swamp ; return this;

}

@Override public

Ogre build () {

if ( name

null ) {

throw Internal. missingRequiredFields ( name , "name" ) ;

}

return new Ogre( name , layers , swamp , super .buildUnknownFields()) ;

} } Internal. checkElementsNotNull (layers) ;

if ( name

null ) {

throw Internal. missingRequiredFields ( name , "name" ) ;

}

Slide 33

Slide 33

public static final class Builder extends Message.Builder<Ogre , Builder> {

public String name ; public List<Integer> layers ; public String swamp ; public Builder () {

layers = Internal. newMutableList () ;

}

public Builder name (String name) {

this . name = name ; return this;

}

public Builder layers (List<Integer> layers) { Internal. checkElementsNotNull (layers) ; this . layers = layers ; return this;

}

public Builder swamp (String swamp) {

this . swamp = swamp ; return this;

}

@Override public

Ogre build () {

if ( name

null ) {

throw Internal. missingRequiredFields ( name , "name" ) ;

}

return new Ogre( name , layers , swamp , super .buildUnknownFields()) ;

} }

Slide 34

Slide 34

class Ogre @JvmOverloads constructor (

@JvmField val name : String , @JvmField val layers : List<Int>

@JvmField val 

swamp : String?

unknownFields: ByteString = ByteString. EMPTY ) : Message<Ogre , Ogre.Builder>( ADAPTER , unknownFields)

@JvmField val name : String , @JvmField val layers : List<Int> = emptyList () , @JvmField val swamp : String? = null ,

Slide 35

Slide 35

val shrek = Ogre(

name = "shrek" ,

layers = listOf ( 1 , 2 ) ,

swamp = null )

Slide 36

Slide 36

Ogre shrek = new Ogre() ;

Slide 37

Slide 37

Ogre shrek = new Ogre( "Shrek" , Arrays. asList ( 1 , 2 ) , "Shrek" ) ;

Slide 38

Slide 38

Java Interop

Slide 39

Slide 39

class

Ogre(

@JvmField val name : String , @JvmField val layers : List<Int> = emptyList () , @JvmField val swamp : String? = null

) interface

@JvmField val name : String , @JvmField val layers : List<Int> = emptyList () , @JvmField val swamp : String? = null

Slide 40

Slide 40

interface Ogre {

val name : String

val layers : List<Int>

val swamp : String? }

Slide 41

Slide 41

interface Ogre {

val name : String

val layers : List<Int>

val swamp : String? }

shrek.getLayers() ;

Slide 42

Slide 42

inline fun < reified T

Ogre. findFriendOfType (): T ? {

for (friend in friends ()) {

if (friend is T ) return friend }

return null }

Slide 43

Slide 43

inline fun < reified T

Ogre. findFriendOfType (): T ? {

for (friend in friends ()) {

if (friend is T ) return friend }

return null } 
 
 shrek.findFriendOfType<Donkey>()

Slide 44

Slide 44

inline fun < reified T

Ogre. findFriendOfType (): T ? {

for (friend in friends ()) {

if (friend is T ) return friend }

return null } 
 
 shrek.findFriendOfType<Donkey>()

shrek.<Donkey>findFriendOfType() ;

Slide 45

Slide 45

inline fun < reified T

Ogre. findFriendOfType (): T ? {

for (friend a in friends ()) {

if (friend is T ) return friend } Y

return b null } Z

Slide 46

Slide 46

fun < T

Ogre. findFriendOfType (type: Class< T ): T ? {

for (friend in friends ()) {

if (type.isInstance(friend)) return friend as T ? } B

return null } A

inline fun < reified T

Ogre. findFriendOfType (): T ? {

for (friend a in friends ()) {

if (friend is T ) return friend } Y

return b null } Z

findFriendOfType ( ::class. java )

Slide 47

Slide 47

fun < T

Ogre. findFriendOfType (type: Class< T ): T ? {

for (friend in friends ()) {

if (type.isInstance(friend)) return friend as T ? } B

return null } A

inline fun < reified T

Ogre. findFriendOfType (): T ? {

return b findFriendOfType ( T :: class . java ) } Z

Slide 48

Slide 48

interface SwampChangedListener {

fun swampChanged (newSwamp: String) } fun addSwampChangedListener (listener: SwampChangedListener) = …

Slide 49

Slide 49

interface SwampChangedListener {

fun swampChanged (newSwamp: String) } A

fun addSwampChangedListener (listener: SwampChangedListener) = …

shrek.addSwampChangedListener( new SwampChangedListener() {

@Override public void swampChanged ( @NotNull String newSwamp) { P

System.

out .println( "What are you doing in "

  • newSwamp) ;

} }) ;

Slide 50

Slide 50

interface SwampChangedListener {

fun swampChanged (newSwamp: String) } A

fun addSwampChangedListener (listener: SwampChangedListener) = …

shrek.addSwampChangedListener(newSwamp -> { P

System. out .println( "What are you doing in "

  • newSwamp) ; }) ;

Slide 51

Slide 51

interface SwampChangedListener {

fun swampChanged (newSwamp: String) } fun addSwampChangedListener (listener: SwampChangedListener) = …

Slide 52

Slide 52

interface SwampChangedListener {

fun swampChanged (newSwamp: ( String) : Unit

} fun addSwampChangedListener (listener: SwampChangedListener) = … shrek.addSwampChangedListener( object : SwampChangedListener {

override fun swampChanged (newSwamp: String) { System. out .println( "What are you doing in $ newSwamp " ) } }) KT-7770

Slide 53

Slide 53

fun addSwampChangedListener (listener: (String) -> Unit) = …

Slide 54

Slide 54

fun addSwampChangedListener (listener: (String) -> Unit) = …

shrek.addSwampChangedListener { newSwamp ->

System. out .println( "What are you doing in $ newSwamp " ) }

Slide 55

Slide 55

fun addSwampChangedListener (listener: (String) -> Unit) = …

shrek.addSwampChangedListener { newSwamp ->

System. out .println( "What are you doing in $ newSwamp " ) }

shrek.addSwampChangedListener(newSwamp -> { System. out .println( "What are you doing in "

  • newSwamp) ; return Unit. INSTANCE ; }) ; KT-21018

Slide 56

Slide 56

fun addSwampChangedListener (listener: SwampChangedListener) = …

public interface SwampChangedListener {

void swampChanged (String newSwamp) ; } Z

Slide 57

Slide 57

fun addSwampChangedListener (listener: SwampChangedListener) = …

shrek.addSwampChangedListener(SwampChangedListener { newSwamp ->

System. out .println( "What are you doing in $ newSwamp " ) } )

public interface SwampChangedListener {

void swampChanged (String newSwamp) ; } Z

Slide 58

Slide 58

fun addSwampChangedListener (listener: SwampChangedListener) = … public interface SwampChangedListener {

void swampChanged (String newSwamp) ; } Z

shrek.addSwampChangedListener(newSwamp -> { System. out .println( "What are you doing in "

  • newSwamp) ; }) ; shrek.addSwampChangedListener(SwampChangedListener { newSwamp ->

System. out .println("What are you doing in $newSwamp") } )

Slide 59

Slide 59

sealed class Optional< T : Any>

data class Some< T : Any>( val value : T ): Optional< T

() object None : Optional<Nothing>()

Slide 60

Slide 60

sealed class Optional< T : Any>

data class Some< T : Any>( val value : T ): Optional< T

() object None : Optional<Nothing>()

fun < T : Any> T ?. asOptional () = if ( this

null ) None else Some( this )

Slide 61

Slide 61

@file:JvmName ( "Optionals" )

sealed class Optional< T : Any>

data class Some< T : Any>( val value : T ): Optional< T

() object None : Optional<Nothing>()

@JvmName ( "ofNullable" )

fun < T : Any> T ?. asOptional () = if ( this

null ) None else Some( this )

Slide 62

Slide 62

sealed class Optional< T : Any> {

companion object {

@JvmName ( "ofNullable" ) @JvmStatic fun < T

:

Any> T ?. asOptional ()

=

if ( this

null ) None else Some( this )

} Y

} Z

data class Some< T : Any>( val value : T ): Optional< T

() object None : Optional<Nothing>() @file:JvmName("Optionals ") KT-15286

Slide 63

Slide 63

sealed class Optional< T : Any> {

companion object {

@JvmStatic fun < T

:

Any> ofNullable (value: T ?) = value. asOptional () } Y

} Z

data class Some< T : Any>( val value : T ): Optional< T

() object None : Optional<Nothing>() fun < T

:

Any> T ?. asOptional () = if ( this

null ) None else Some( this ) @JvmName KT-15286

Slide 64

Slide 64

@file:JvmName( "-Optionals" ) sealed class Optional< T : Any> {

companion object {

@JvmStatic fun < T

:

Any> ofNullable (value: T ?) = value. asOptional () } Y

} Z

data class Some< T : Any>( val value : T ): Optional< T

() object None : Optional<Nothing>() fun < T

:

Any> T ?. asOptional () = if ( this

null ) None else Some( this ) KT-15286

Slide 65

Slide 65

class Foo (

val bar : Nothing , val listBar : List<Nothing> )

Slide 66

Slide 66

class Foo (

val bar : Nothing , val listBar : List<Nothing> ) Void bar = foo.getBar() ; List listBar = foo.getListBar() ;

Slide 67

Slide 67

KotlinPoet

Slide 68

Slide 68

Type

Slide 69

Slide 69

Type Class

Slide 70

Slide 70

Type Class Parameterized Type

Slide 71

Slide 71

Type String Map<String,Int>

Slide 72

Slide 72

val stringClass: KClass<String> = String:: class

Slide 73

Slide 73

val stringClass: KClass<String> = String:: class val stringName: ClassName = stringClass. asClassName ()

Slide 74

Slide 74

val stringClass: KClass<String> = String:: class val stringName: ClassName = stringClass. asClassName ()

import kotlin.String val foo : String = ""

Slide 75

Slide 75

val stringClass: KClass<String> = String:: class val stringName: ClassName = stringClass. asClassName ()

import kotlin.String val foo : String = ""

class String

Slide 76

Slide 76

val stringClass: KClass<String> = String:: class val stringName: ClassName = stringClass. asClassName ()

class String {

val foo : kotlin.String = "" }

Slide 77

Slide 77

val stringClass: KClass<String> = String:: class val stringName: ClassName = stringClass. asClassName ()

Slide 78

Slide 78

val stringClass: KClass<String> = String:: class val stringName: ClassName = stringClass. asClassName ()

val mapStringToInt

= ParameterizedTypeName.get( Map:: class . asTypeName () , stringName , Int:: class . asTypeName ())

Slide 79

Slide 79

val stringClass: KClass<String> = String:: class val stringName: ClassName = stringClass. asClassName ()

val mapStringToInt

= ParameterizedTypeName.get( Map:: class . asTypeName () , stringName , Int:: class . asTypeName ())

val nullableMap = mapStringToInt.asNullable()

Slide 80

Slide 80

val foo = PropertySpec.builder( "foo" , String:: class ) .initializer( "%S" , "foo" ) .build()

Slide 81

Slide 81

val foo = PropertySpec.builder( "foo" , String:: class ) .initializer( "%S" , "foo" ) .build()

String:: class

Slide 82

Slide 82

val foo = PropertySpec.builder( "foo" , String:: class ) .initializer( "%S" , "foo" ) .build()

"%S" ,

"foo"

Slide 83

Slide 83

val foo = PropertySpec.builder( "foo" , String:: class ) .initializer( "%S" , "foo" ) .build()

Slide 84

Slide 84

val foo = PropertySpec.builder( "foo" , String:: class ) .initializer( "%S" , "foo" ) .build()

println (foo) val

foo : kotlin.String = "foo" X

Slide 85

Slide 85

val foo = PropertySpec.builder( "foo" , String:: class ) .initializer( "%S" , "foo

bar" ) .build()

println (foo) val

foo : kotlin.String = "foo

bar" X

Slide 86

Slide 86

val foo = PropertySpec.builder( "foo" , String:: class ) .initializer( "%S" , "foo

bar" ) .build()

println (foo) val

foo : kotlin.String = "foo

bar" X

kotlin.String

Slide 87

Slide 87

val foo = PropertySpec.builder( "foo" , String:: class ) .initializer( "%S" , "foo

bar" ) .build()

val file = FileSpec.builder( "com.example" , "KotlinConf.kt" ) .addProperty(foo) .build()

println (file)

package com.example import kotlin.String val

foo : String = "foo

bar" X

foo

Slide 88

Slide 88

PropertySpec.builder( "foo" , String:: class ) .initializer( "%S" , "foo

bar" ) .build() package com.example import kotlin.String val

foo : String = "foo

bar" X

Slide 89

Slide 89

FunSpec.builder( "main" ) .addParameter( "args" , String:: class, VARARG ) .build() package com.example import kotlin.String fun main ( vararg args: String)

{ }

Slide 90

Slide 90

TypeSpec.classBuilder( "User" ) .addModifiers( DATA ) .build() package com.example data class User

Slide 91

Slide 91

TypeSpec.classBuilder( "User" ) .addModifiers( DATA ) .build() package com.example data class User

Slide 92

Slide 92

TypeSpec.classBuilder( "User" ) .addModifiers( DATA ) .addProperty(PropertySpec.builder( "name" , String:: class ).build()) .build() Z

package com.example data class User { Y

val

name : String } X

Slide 93

Slide 93

TypeSpec.classBuilder( "User" ) .addModifiers( DATA ) .addProperty(PropertySpec.builder( "name" , String:: class ).build())

.primaryConstructor(FunSpec.constructorBuilder() .addParameter( "name" , String:: class ) .build()) A

.build()

Z

package com.example data class User(name: String) G { Y

val

name : String } X

Slide 94

Slide 94

                name: String

TypeSpec.classBuilder( "User" ) .addModifiers( DATA ) .addProperty(PropertySpec.builder( "name" , String:: class )

    .initializer(

"name" ) .build()) B

.primaryConstructor(FunSpec.constructorBuilder() .addParameter( "name" , String:: class ) .build()) A

.build() 

package com.example data class User( val

name : String) G

Slide 95

Slide 95

TypeSpec.classBuilder( "User" ) .addModifiers( DATA ) .addProperty(PropertySpec.builder( "name" , String:: class )

    .initializer(

"name.toLowerCase()" ) .build()) B

.primaryConstructor(FunSpec.constructorBuilder() .addParameter( "name" , String:: class ) .build()) A

.build() 

package com.example data class User(name: String) G {

val

name : String = name. toLowerCase () } X

Slide 96

Slide 96

FunSpec.builder( "seconds" ) .receiver(Long:: class ) .returns(Duration:: class ) .addStatement( "return %T.ofSeconds(this)" , Duration:: class ) .build() package com.example import java.time.Duration

import kotlin.Long

fun Long. seconds (): Duration = Duration.ofSeconds( this )

Slide 97

Slide 97

FunSpec.builder( "seconds" ) .receiver(Long:: class ) .returns(Duration:: class )

.addStatement(

"require(this >= 0L)" )

.addStatement(

"return %T.ofSeconds(this)" , Duration:: class ) .build() package com.example import java.time.Duration

import kotlin.Long

fun Long. seconds (): Duration {

require ( this

= 0L )

return Duration.ofSeconds( this )

}

Slide 98

Slide 98

FunSpec.builder( "seconds" ) .receiver(Long:: class ) .returns(Duration:: class )

.addStatement(

"require(this >= 0L)" )

.addStatement(

"return %T.ofSeconds(this)" , Duration:: class ) .build()

Slide 99

Slide 99

val longSeconds = FunSpec.builder( "seconds" ) .receiver(Long:: class ) .returns(Duration:: class )

.addStatement(

"require(this >= 0L)" )

.addStatement(

"return %T.ofSeconds(this)" , Duration:: class ) .build()

Slide 100

Slide 100

val longSeconds = FunSpec.builder( "seconds" ) .receiver(Long:: class ) .returns(Duration:: class )

.addStatement(

"require(this >= 0L)" )

.addStatement(

"return %T.ofSeconds(this)" , Duration:: class ) .build()

FunSpec.builder( "main" ) .addParameter( "args" , String:: class,

VARARG ) .addStatement( "println(%L.%N())" ,

2L , longSeconds) .build()

Slide 101

Slide 101

val longSeconds = FunSpec.builder( "seconds" ) .receiver(Long:: class ) .returns(Duration:: class )

.addStatement(

"require(this >= 0L)" )

.addStatement(

"return %T.ofSeconds(this)" , Duration:: class ) .build()

FunSpec.builder( "main" ) .addParameter( "args" , String:: class,

VARARG ) .addStatement( "println(%L.%N())" ,

2L , longSeconds) .build()

%N

longSeconds

Slide 102

Slide 102

val longSeconds = FunSpec.builder( "seconds" ) .receiver(Long:: class ) .returns(Duration:: class )

.addStatement(

"require(this >= 0L)" )

.addStatement(

"return %T.ofSeconds(this)" , Duration:: class ) .build()

FunSpec.builder( "main" ) .addParameter( "args" , String:: class,

VARARG ) .addStatement( "println(%L.%N())" ,

2L , longSeconds) .build() fun

main ( vararg args: String) {

println ( 2L . seconds ()) }

Slide 103

Slide 103

val code = CodeBlock.builder()

Slide 104

Slide 104

val code = CodeBlock.builder() code.addStatement( "val foo = %T.MIN_VALUE" , Int:: class )

Slide 105

Slide 105

val code = CodeBlock.builder() code.addStatement( "val foo = %T.MIN_VALUE" , Int:: class )

code.add( "val bar = " ) when (answer) {

YES -> code.add( "0L" )

NO -> code.add( "%T.MIN_VALUE" , Int:: class ) } code.add( ".toString()

" )

Slide 106

Slide 106

val code = CodeBlock.builder() code.addStatement( "val foo = %T.MIN_VALUE" , Int:: class )

code.add( "val bar = " ) when (answer) {

YES -> code.add( "0L" )

NO -> code.add( "%T.MIN_VALUE" , Int:: class ) } code.add( ".toString()

" )

code.beginControlFlow( "if (bar.isEmpty())" ) .addStatement( "println(%S)" , "Empty!" ) .nextControlFlow( "else" ) .addStatement( "println(bar)" ) .endControlFlow()

Slide 107

Slide 107

val intMin = CodeBlock.of( "%T.MIN_VALUE" , Int:: class ) val intMax = CodeBlock.of( "%T.MAX_VALUE" , Int:: class ) val longMin = CodeBlock.of( "%T.MIN_VALUE" , Long:: class ) val longMax = CodeBlock.of( "%T.MAX_VALUE" , Long:: class ) val values = listOf (intMin , intMax , longMin , longMax)

Slide 108

Slide 108

val intMin = CodeBlock.of( "%T.MIN_VALUE" , Int:: class ) val intMax = CodeBlock.of( "%T.MAX_VALUE" , Int:: class ) val longMin = CodeBlock.of( "%T.MIN_VALUE" , Long:: class ) val longMax = CodeBlock.of( "%T.MAX_VALUE" , Long:: class ) val values = listOf (intMin , intMax , longMin , longMax) // elsewhere val list = values. joinToCode ( prefix = "listOf(" , suffix = ")" )

Slide 109

Slide 109

val intMin = CodeBlock.of( "%T.MIN_VALUE" , Int:: class ) val intMax = CodeBlock.of( "%T.MAX_VALUE" , Int:: class ) val longMin = CodeBlock.of( "%T.MIN_VALUE" , Long:: class ) val longMax = CodeBlock.of( "%T.MAX_VALUE" , Long:: class ) val values = listOf (intMin , intMax , longMin , longMax) // elsewhere val list = values. joinToCode ( prefix = "listOf(" , suffix = ")" )

listOf (Int. MIN_VALUE , Int. MAX_VALUE , Long. MIN_VALUE , Long. MAX_VALUE )

Slide 110

Slide 110

inline fun < reified T , R : CharSequence>

(String.() -> 

R ). crazy ( noinline foo: T .( R ?) -> Unit)

where T : Runnable , T : Closeable

= 

42L

Slide 111

Slide 111

val typeT = TypeVariableName( "T" , Runnable:: class, Closeable:: class ) val typeR = TypeVariableName( "R" , CharSequence:: class ) val stringExtToR = LambdaTypeName.get(String:: class . asClassName () , returnType = typeR) val tRtoUnit = LambdaTypeName.get(typeT ,

parameters = typeR.asNullable() , returnType = UNIT ) val crazy = FunSpec.builder( "crazy" ) .addModifiers( INLINE ) .receiver(stringExtToR) .addTypeVariable(typeT.reified()) .addTypeVariable(typeR) .addParameter( "foo" , tRtoUnit , NOINLINE ) .addStatement( "return 42L" ) .build()

inline fun < reified T , R : CharSequence>

(String.() -> 

R ). crazy ( noinline foo: T .( R ?) -> Unit)

where T : Runnable , T : Closeable

= 

42L

Slide 112

Slide 112

Kotlin Compatible Code

Slide 113

Slide 113

@Nullable public String getSwamp () {

return swamp ; }

Slide 114

Slide 114

@Nullable public String getSwamp () {

return swamp ; }

val swamp: String? = shrek. swamp

Slide 115

Slide 115

Bytecode Build tool

Slide 116

Slide 116

Bytecode Build tool

Slide 117

Slide 117

interface Foo {

val bar : String }

Slide 118

Slide 118

public abstract interface com/sample/Foo {

// access flags 0x401

public abstract getBar()Ljava/lang/String ;

@Lorg/jetbrains/annotations/NotNull ; () // invisible

LOCALVARIABLE 

this Lcom/sample/Foo ; L0 L1 0

@Lkotlin/Metadata ; ( 
 mv={ 1 ,

1 ,

7 } , 
 bv={ 1 ,

0 ,

2 } , 
 k= 1 , 
 d1={ “…” } , 
 d2={ "Lcom/sample/Foo;" ,

"" ,

"bar" ,

"" ,

“getBar" } 


)

// compiled from: Foo.kt

}

Slide 119

Slide 119

public abstract interface com/sample/Foo {

// access flags 0x401

public abstract getBar()Ljava/lang/String ;

@Lorg/jetbrains/annotations/NotNull ; () // invisible

LOCALVARIABLE 

this Lcom/sample/Foo ; L0 L1 0

@Lkotlin/Metadata ; ( 
 mv={ 1 ,

1 ,

7 } , 
 bv={ 1 ,

0 ,

2 } , 
 k= 1 , 
 d1={ “…” } , 
 d2={ "Lcom/sample/Foo;" ,

"" ,

"bar" ,

"" ,

“getBar" } 


)

// compiled from: Foo.kt

} goo.gl/GcT9gz

Slide 120

Slide 120

github.com/Takhion/kotlin-metadata

org.jetbrains.kotlin.serialization .ProtoBuf.Class

Slide 121

Slide 121

github.com/Takhion/kotlin-metadata

org.jetbrains.kotlin.serialization .ProtoBuf.Class

Slide 122

Slide 122

github.com/Takhion/kotlin-metadata

org.jetbrains.kotlin.serialization .ProtoBuf.Class

Slide 123

Slide 123

github.com/Takhion/kotlin-metadata

org.jetbrains.kotlin.serialization .ProtoBuf.Class

Slide 124

Slide 124

github.com/Takhion/kotlin-metadata

org.jetbrains.kotlin.serialization .ProtoBuf.Class

Slide 125

Slide 125

github.com/Takhion/kotlin-metadata

org.jetbrains.kotlin.serialization .ProtoBuf.Class

Slide 126

Slide 126

public abstract interface com/sample/Foo {

// access flags 0x401

public abstract

getBar ()Ljava/lang/String ;

@Lorg/jetbrains/annotations/NotNull ; () // invisible

LOCALVARIABLE 

this Lcom/sample/Foo ; L0 L1 0

@Lkotlin/Metadata ; ( 
 mv={ 1 ,

1 ,

7 } , 
 bv={ 1 ,

0 ,

2 } , 
 k= 1 , 
 d1={ “…” } , 
 d2={ "Lcom/sample/Foo;" ,

"" ,

"bar" ,

"" ,

“ getBar " } 


)

// compiled from: Foo.kt

}

Slide 127

Slide 127

Bytecode

Slide 128

Slide 128

Bytecode

Slide 129

Slide 129

public abstract interface com/sample/Foo {

// access flags 0x401

public abstract getBar()Ljava/lang/String ;

@Lorg/jetbrains/annotations/NotNull ; () // invisible

LOCALVARIABLE 

this Lcom/sample/Foo ; L0 L1 0

@Lkotlin/Metadata ; ( 
 mv={ 1 ,

1 ,

7 } , 
 bv={ 1 ,

0 ,

2 } , 
 k= 1 , 
 d1={ “…” } , 
 d2={ "Lcom/sample/Foo;" ,

"" ,

"bar" ,

"" ,

“getBar" } 
 ) g

// compiled from: Foo.kt

} A

Slide 130

Slide 130

public abstract interface com/sample/Foo {

// access flags 0x401

public abstract getBar()Ljava/lang/String ;

@Lorg/jetbrains/annotations/NotNull ; () // invisible

LOCALVARIABLE 

this Lcom/sample/Foo ; L0 L1 0

@Lkotlin/Metadata ; ( 
 mv={ 1 ,

1 ,

7 } , 
 bv={ 1 ,

0 ,

2 } , 
 k= 1 , 
 d1={ “…” } , 
 d2={ "Lcom/sample/Foo;" ,

"" ,

"bar" ,

"" ,

“getBar" } 
 ) g

// compiled from: Foo.kt

} A

Slide 131

Slide 131

public abstract interface com/sample/Foo {

// access flags 0x401

public abstract getBar()Ljava/lang/String ;

@Lorg/jetbrains/annotations/NotNull ; () // invisible

LOCALVARIABLE 

this Lcom/sample/Foo ; L0 L1 0

@Lkotlin/Metadata ; ( 
 mv={ 1 ,

1 ,

7 } , 
 bv={ 1 ,

0 ,

2 } , 
 k= 1 , 
 d1={ “…” } , 
 d2={ "Lcom/sample/Foo;" ,

"" ,

"bar" ,

"" ,

“getBar" } 


)

// compiled from: Foo.kt

} { A

AnnotationVisitor av1 = av0.visitArray( "d2" ) ;

av1.visit( null, "Lcom/sample/Foo;" ) ;

av1.visit( null, "" ) ;

av1.visit( null, "bar" ) ;

av1.visit( null, "" ) ;

av1.visit( null, "getBar" ) ;

av1.visit( null, "()I" ) ;

av1.visitEnd() ; } B

{ C

mv = cw.visitMethod( ACC_PUBLIC + ACC_ABSTRACT ,

"getBar" , "()I" , null, null ) ;

mv.visitEnd() ; } D

Slide 132

Slide 132

{ A

AnnotationVisitor av1 = av0.visitArray( "d2" ) ;

av1.visit( null, "Lcom/sample/Foo;" ) ;

av1.visit( null, "" ) ;

av1.visit( null, "bar" ) ;

av1.visit( null, "" ) ;

av1.visit( null, "getBar" ) ;

av1.visit( null, "()I" ) ;

av1.visitEnd() ; } B

{ C

mv = cw.visitMethod( ACC_PUBLIC + ACC_ABSTRACT ,

"getBar" , "()I" , null, null ) ;

mv.visitEnd() ; } D b

b

Slide 133

Slide 133

{ A

AnnotationVisitor av1 = av0.visitArray( "d2" ) ;

av1.visit( null, "Lcom/sample/Foo;" ) ;

av1.visit( null, "" ) ;

av1.visit( null, "bar" ) ;

av1.visit( null, "" ) ;

av1.visit( null, " bar " ) ;

av1.visit( null, "()I" ) ;

av1.visitEnd() ; } B

{ C

mv = cw.visitMethod( ACC_PUBLIC + ACC_ABSTRACT ,

" bar " , "()I" , null, null ) ;

mv.visitEnd() ; } D

Slide 134

Slide 134

{ A

AnnotationVisitor av1 = av0.visitArray( "d2" ) ;

av1.visit( null, "Lcom/sample/Foo;" ) ;

av1.visit( null, "" ) ;

av1.visit( null, "bar" ) ;

av1.visit( null, "" ) ;

av1.visit( null, " bar " ) ;

av1.visit( null, "()I" ) ;

av1.visitEnd() ; } B

{ C

mv = cw.visitMethod( ACC_PUBLIC + ACC_ABSTRACT ,

" bar " , "()I" , null, null ) ;

mv.visitEnd() ; } D

Slide 135

Slide 135

{ AnnotationVisitor av1 = av0.visitArray( "d2" ) ;

av1.visit( null, "Lcom/sample/Foo;" ) ;

av1.visit( null, "" ) ;

av1.visit( null, "bar" ) ;

av1.visit( null, "" ) ;

av1.visit( null, " bar " ) ;

av1.visit( null, "()I" ) ;

av1.visitEnd() ; } { mv = cw.visitMethod( ACC_PUBLIC + ACC_ABSTRACT ,

" bar " , "()I" , null, null ) ;

mv.visitEnd() ; } public abstract interface com/sample/Foo {

// access flags 0x401

public abstract

bar ()Ljava/lang/String ;

@Lorg/jetbrains/annotations/NotNull ; () // invisible

LOCALVARIABLE 

this Lcom/sample/Foo ; L0 L1 0

@Lkotlin/Metadata ; ( 
 mv={ 1 ,

1 ,

7 } , 
 bv={ 1 ,

0 ,

2 } , 
 k= 1 , 
 d1={ “…” } , 
 d2={ "Lcom/sample/Foo;" ,

"" ,

"bar" ,

"" ,

“ bar ” } 


)

// compiled from: Foo.kt

}

Slide 136

Slide 136

class KotlinFoo( override val bar: Int): Foo 
 
 class JavaFoo implements Foo { @Override

public int bar() {

return 0 ;

} }

Slide 137

Slide 137

void setPadding ( int l , int t , int r , int b) {

// … }

Slide 138

Slide 138

void setPadding ( int l , int t , int r , int b) {

// … } z

view.setPadding( 10 , 0 , 0 , 10 )

Slide 139

Slide 139

void setPadding ( int l , int t , int r , int b) {

// … } z

view.setPadding( left = 10 , bottom = 10 )

Slide 140

Slide 140

Bytecode

Slide 141

Slide 141

Multiplatform

Slide 142

Slide 142

Bytecode

Slide 143

Slide 143

Bytecode

Slide 144

Slide 144

Bytecode LLVM

Slide 145

Slide 145

enum class Direction { NORTH , SOUTH , EAST , WEST } class GamePeice( movement: Set<Direction> = EnumSet. of (Direction. NORTH ) ) Z

Slide 146

Slide 146

enum class Direction { NORTH , SOUTH , EAST , WEST } class GamePeice( movement: Set<Direction> = EnumSet. of (Direction. NORTH ) ) Z EnumSet. of

Slide 147

Slide 147

import java.util.EnumSet enum class Direction { NORTH , SOUTH , EAST , WEST } class GamePeice( movement: Set<Direction> = EnumSet. of (Direction. NORTH ) ) Z

                           s   O
                           EnumSet.

of

Slide 148

Slide 148

enum class Direction { NORTH , SOUTH , EAST , WEST } class GamePeice( movement: Set<Direction> = setOf (Direction. NORTH ) ) Z

S o

Slide 149

Slide 149

import com.google.common.collect

@AutoImplement interface Party {

val people : ImmutableList<Person> }

Slide 150

Slide 150

import com.google.common.collect

@AutoImplement interface Party {

val people : ImmutableList<Person> }

import com.google.common.collect

@Generated class AutoParty( override val people : ImmutableList<Person>) : Party

Slide 151

Slide 151

CREATE TABLE user(

name TEXT NOT NULL,

location TEXT AS android.location.Location )

Slide 152

Slide 152

CREATE TABLE user(

name TEXT NOT NULL,

location TEXT AS android.location.Location ) import android.location.Location data class User(

val

name : String,

val

location : Location )

Slide 153

Slide 153

@file:JvmName ( "ByteStrings" ) @JvmName ( "from" ) fun ByteArray. asByteString (): ByteString = …

Slide 154

Slide 154

@file:JvmName ( "ByteStrings" ) @JvmName ( "from" ) fun ByteArray. asByteString (): ByteString = …

byte [] bytes = …

ByteString b = ByteStrings. from (bytes) ;

Slide 155

Slide 155

@file:JvmName ( "ByteStrings" ) @JvmName ( "from" ) fun ByteArray. asByteString (): ByteString = …

byte [] bytes = …

ByteString b = ByteStrings. from (bytes) ; Cannot access 'JvmName': it is internal in 'kotlin.jvm' s

KT-19507

Slide 156

Slide 156

@JsName ( "from" ) fun ByteArray. asByteString (): ByteString = … @file:JvmName("ByteStrings")

Slide 157

Slide 157

@ JsName ( "from" ) fun ByteArray. asByteString (): ByteString = … @file:JvmName("ByteStrings")

KT-19508

Slide 158

Slide 158

Verbosity is okay. API is the #1 priority.

Slide 159

Slide 159

Verbosity is okay. API is the #1 priority. If you do any kind of Java codegen, keep Kotlin in mind.

Slide 160

Slide 160

Verbosity is okay. API is the #1 priority. If you do any kind of Java codegen, keep Kotlin in mind. Don’t depend on platform types unless the user does.

Slide 161

Slide 161

KotlinPoet 0.6.0 released!

Slide 162

Slide 162

@Strongolopolis & @JakeWharton Kotlin Code Generation