KBuilders

Kotlin Type-Safe Builders Everywhere!

Download JAR View on GitHub

KBuilders turns your Java builders into beautiful Type-Safe Builders. It is compatible with Protocol Buffers, Wire, and most generic Builders.

val bilbo = buildHobbit {
    firstName = "Bilbo"
    lastName = "Baggins"
    carrying = listOf(ring, pipe)
    weapon = buildWeapon {
        name = "Sting"
        size = Size.SMALL
        detects = Race.GOBLINS
    }
}

// FRODOCOL BUFFERS
val frodo = bilbo.rebuild {
    firstName = "Frodo" 
}

Usage

KBuilders is distributed as a standalone JAR and we recommend integrating it into your existing protoc scripts.

#!/bin/bash

# Build your protobufs as usual
protoc --java_out=$JAVA_OUT --proto_path=`find $PROTO_ROOT -name '*.proto'`

# Run kbuilders on the resulting files
java -jar kbuilders.jar --javaRoot=$JAVA_OUT --kotlinRoot=$KOTLIN_OUT

How it works

KBuilders scans through your Java source looking for internal classes named Builder and generates K combinator extension methods. Because all generated methods are inline, there should theoretically be no added footprint or runtime impact.

// generated Hobbit.kt

public inline fun buildHobbit(fn: Hobbit.Builder.() -> Unit): Hobbit {
    val builder = Hobbit.Builder()
    builder.fn()
    return builder.build()
}

public inline fun Hobbit.rebuild(fn: Hobbit.Builder.() -> Unit): Hobbit {
    val builder = Hobbit.Builder(this)
    builder.fn()
    return builder.build()
}

Pull requests are appreciated, and please let us know what you think!

License

Copyright 2015 Level Money, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.