Generating Kotlin Code (KotlinConf 2017)

E68309f117985270285ade8082f4877d?s=47 Jake Wharton
November 03, 2017

Generating Kotlin Code (KotlinConf 2017)

Kotlin provides simpler options than traditional Java patterns like builders and factories often found in the generated code. By using Kotlin to generate an API, you can not only create a pleasant experience from both languages, but also unlock the possibility of targeting native and JS. This talk will cover the tools needed to generate Kotlin code and also the features available in Kotlin that can improve your generated code.

Video: coming soon

E68309f117985270285ade8082f4877d?s=128

Jake Wharton

November 03, 2017
Tweet

Transcript

  1. Kotlin Code Generation Alec Strong & Jake Wharton

  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 )
  3. Bytecode

  4. Protocol Buffers

  5. Protocol Buffers SQL

  6. Protocol Buffers SQL Swagger

  7. Protocol Buffers SQL Swagger Android XML

  8. Protocol Buffers SQL Swagger Android XML YAML

  9. SQL Swagger Android XML YAML Mirrors/Elements

  10. Swagger Android XML YAML Mirrors/Elements PSI

  11. Android XML YAML Mirrors/Elements PSI UAST

  12. YAML Mirrors/Elements PSI UAST ???

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

    ???
  14. Protocol Buffers

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

    name = 1; repeated int32 layers = 2; optional string swamp = 3; }
  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; }
  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;
  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
  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)
  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
  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; }
  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)
  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
  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); Se
  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() }
  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)
  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)
  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
  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
  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)
  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()); } }
  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"); }
  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()); } }
  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,
  35. val shrek = Ogre( name = "shrek", layers = listOf(1,

    2), swamp = null )
  36. Ogre shrek = new Ogre();

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

  38. Java Interop

  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
  40. interface Ogre { val name: String val layers: List<Int> val

    swamp: String? }
  41. interface Ogre { val name: String val layers: List<Int> val

    swamp: String? } shrek.getLayers();
  42. inline fun <reified T> Ogre.findFriendOfType(): T? { for (friend in

    friends()) { if (friend is T) return friend } return null }
  43. inline fun <reified T> Ogre.findFriendOfType(): T? { for (friend in

    friends()) { if (friend is T) return friend } return null }
 
 shrek.findFriendOfType<Donkey>()
  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();
  45. inline fun <reified T> Ogre.findFriendOfType(): T? { for (friendain friends())

    { if (friend is T) return friend }Y returnbnull }Z
  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 (friendain friends()) { if (friend is T) return friend }Y returnbnull }Z findFriendOfType( ::class.java)
  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? { returnbfindFriendOfType(T::class.java) }Z
  48. interface SwampChangedListener { fun swampChanged(newSwamp: String) } fun addSwampChangedListener(listener: SwampChangedListener)

    = …
  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); } });
  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); });
  51. interface SwampChangedListener { fun swampChanged(newSwamp: String) } fun addSwampChangedListener(listener: SwampChangedListener)

    = …
  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
  53. fun addSwampChangedListener(listener: (String) -> Unit) = …

  54. fun addSwampChangedListener(listener: (String) -> Unit) = … shrek.addSwampChangedListener { newSwamp

    -> System.out.println("What are you doing in $newSwamp") }
  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
  56. fun addSwampChangedListener(listener: SwampChangedListener) = … public interface SwampChangedListener { void

    swampChanged(String newSwamp); }Z
  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
  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") })
  59. sealed class Optional<T : Any> data class Some<T : Any>(val

    value: T): Optional<T>() object None : Optional<Nothing>()
  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)
  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)
  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>() KT-15286 @file:JvmName("Optionals")
  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) KT-15286 @JvmName
  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
  65. class Foo ( val bar: Nothing, val listBar: List<Nothing> )

  66. class Foo ( val bar: Nothing, val listBar: List<Nothing> )

    Void bar = foo.getBar(); List listBar = foo.getListBar();
  67. KotlinPoet

  68. Type

  69. Type Class

  70. Type Class Parameterized Type

  71. Type String Map<String,Int>

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

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

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

    import kotlin.String val foo: String = ""
  75. val stringClass: KClass<String> = String::class val stringName: ClassName = stringClass.asClassName()

    import kotlin.String val foo: String = "" class String
  76. val stringClass: KClass<String> = String::class val stringName: ClassName = stringClass.asClassName()

    class String { val foo: kotlin.String = "" }
  77. val stringClass: KClass<String> = String::class val stringName: ClassName = stringClass.asClassName()

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

    val mapStringToInt = ParameterizedTypeName.get( Map::class.asTypeName(), stringName, Int::class.asTypeName())
  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()
  80. val foo = PropertySpec.builder("foo", String::class) .initializer("%S", "foo") .build()

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

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

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

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

    foo: kotlin.String = "foo"X
  85. val foo = PropertySpec.builder("foo", String::class) .initializer("%S", "foo\tbar") .build() println(foo) val

    foo: kotlin.String = "foo\tbar"X
  86. val foo = PropertySpec.builder("foo", String::class) .initializer("%S", "foo\tbar") .build() println(foo) val

    foo: kotlin.String = "foo\tbar"X kotlin.String
  87. val foo = PropertySpec.builder("foo", String::class) .initializer("%S", "foo\tbar") .build() val file

    = FileSpec.builder("com.example", "KotlinConf.kt") .addProperty(foo) .build() println(file) package com.example import kotlin.String val foo: String = "foo\tbar"X foo
  88. PropertySpec.builder("foo", String::class) .initializer("%S", "foo\tbar") .build() package com.example import kotlin.String val

    foo: String = "foo\tbar"X
  89. FunSpec.builder("main") .addParameter("args", String::class, VARARG) .build() package com.example import kotlin.String fun

    main(vararg args: String) { }
  90. TypeSpec.classBuilder("User") .addModifiers(DATA) .build() package com.example data class User

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

  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
  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
  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
  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
  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)
  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) }
  98. FunSpec.builder("seconds") .receiver(Long::class) .returns(Duration::class) .addStatement("require(this >= 0L)") .addStatement("return %T.ofSeconds(this)", Duration::class) .build()

  99. val longSeconds = FunSpec.builder("seconds") .receiver(Long::class) .returns(Duration::class) .addStatement("require(this >= 0L)") .addStatement("return

    %T.ofSeconds(this)", Duration::class) .build()
  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()
  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
  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()) }
  103. val code = CodeBlock.builder()

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

  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()\n")
  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()\n") code.beginControlFlow("if (bar.isEmpty())") .addStatement("println(%S)", "Empty!") .nextControlFlow("else") .addStatement("println(bar)") .endControlFlow()
  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)
  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 = ")")
  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)
  110. inline fun <reified T, R : CharSequence> (String.() -> R).crazy(noinline

    foo: T.(R?) -> Unit) where T : Runnable, T : Closeable = 42L
  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
  112. Kotlin Compatible Code

  113. @Nullable public String getSwamp() { return swamp; }

  114. @Nullable public String getSwamp() { return swamp; } val swamp:

    String? = shrek.swamp
  115. Bytecode Build tool

  116. Bytecode Build tool

  117. interface Foo { val bar: String }

  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 }
  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
  120. github.com/Takhion/kotlin-metadata org.jetbrains.kotlin.serialization.ProtoBuf.Class

  121. github.com/Takhion/kotlin-metadata org.jetbrains.kotlin.serialization.ProtoBuf.Class

  122. github.com/Takhion/kotlin-metadata org.jetbrains.kotlin.serialization.ProtoBuf.Class

  123. github.com/Takhion/kotlin-metadata org.jetbrains.kotlin.serialization.ProtoBuf.Class

  124. github.com/Takhion/kotlin-metadata org.jetbrains.kotlin.serialization.ProtoBuf.Class

  125. github.com/Takhion/kotlin-metadata org.jetbrains.kotlin.serialization.ProtoBuf.Class

  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 }
  127. Bytecode

  128. Bytecode

  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
  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
  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
  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
  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
  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
  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 }
  136. class KotlinFoo(override val bar: Int): Foo
 
 class JavaFoo implements

    Foo { @Override public int bar() { return 0; } }
  137. void setPadding(int l, int t, int r, int b) {

    // … }
  138. void setPadding(int l, int t, int r, int b) {

    // … }z view.setPadding(10, 0, 0, 10)
  139. void setPadding(int l, int t, int r, int b) {

    // … }z view.setPadding(left = 10, bottom = 10)
  140. Bytecode

  141. Multiplatform

  142. Bytecode

  143. Bytecode

  144. Bytecode LLVM

  145. enum class Direction { NORTH, SOUTH, EAST, WEST } class

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

    GamePeice( movement: Set<Direction> = EnumSet.of(Direction.NORTH) )Z EnumSet.of
  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
  148. enum class Direction { NORTH, SOUTH, EAST, WEST } class

    GamePeice( movement: Set<Direction> = setOf(Direction.NORTH) )Z S o
  149. import com.google.common.collect @AutoImplement interface Party { val people: ImmutableList<Person> }

  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
  151. CREATE TABLE user( name TEXT NOT NULL, location TEXT AS

    android.location.Location )
  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 )
  153. @file:JvmName("ByteStrings") @JvmName("from") fun ByteArray.asByteString(): ByteString = …

  154. @file:JvmName("ByteStrings") @JvmName("from") fun ByteArray.asByteString(): ByteString = … byte[] bytes =

    … ByteString b = ByteStrings.from(bytes);
  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' KT-19507 s
  156. @JsName("from") fun ByteArray.asByteString(): ByteString = … @file:JvmName("ByteStrings")

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

  158. Verbosity is okay. API is the #1 priority.

  159. Verbosity is okay. API is the #1 priority. If you

    do any kind of Java codegen, keep Kotlin in mind.
  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.
  161. KotlinPoet 0.6.0 released!

  162. @Strongolopolis & @JakeWharton Kotlin Code Generation