Search code examples
androidgradle-kotlin-dslandroid-jetpack-datastore

Jetpack proto datastore - gradle config with Kotlin dsl


In jetpack datastore, you have to set the gradle plugin task for generating class out of .proto files:

// build.gradle
protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:3.10.0"
    }

    // Generates the java Protobuf-lite code for the Protobufs in this project. See
    // https://github.com/google/protobuf-gradle-plugin#customizing-protobuf-compilation
    // for more information.
    generateProtoTasks {
        all().each { task ->
            task.builtins {
                java {
                    option 'lite'
                }
            }
        }
    }
}

In my project I use Kotlin dsl for my gradle project. After trying to convert this to kotlin dsl, option property is unknown and I can't find it's alternative for kotlin kts

// build.gradle.kts
protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:3.10.0"
    }
    generateProtoTasks {
        all().forEach { task ->
            task.builtins {
                java {
                    option = "lite" // ** option is unknown **
                }
            }
        }
    }
}

Solution

  • To use Jetpack Proto Datastore use the following code for Gradle Kotlin DSL

    // top of file
    import com.google.protobuf.gradle.*
    
    plugins {
        id("com.google.protobuf") version "0.8.12"
        // ...
    }
    
    val protobufVersion = "3.18.0"
    
    dependencies {
      // ...
      implementation("com.google.protobuf:protobuf-javalite:$protobufVersion")
      implementation("androidx.datastore:datastore:1.0.0-alpha03")
    }
    
    protobuf {
        protoc {
            artifact = "com.google.protobuf:protoc:$protobufVersion"
        }
        generateProtoTasks {
            all().forEach { task ->
                task.plugins{
                    create("java") {
                        option("lite")
                    }
                }
            }
        }
    }