29

my project has two different build.gradle files written with groovy Syntax. I´d like to change this groovy written gradle file into a gradle file written with Kotlin Syntax (build.gradle.kts).

I´ll show you the root project build.gradle file.

    // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    //ext.kotlin_version = '1.2-M2'
    ext.kotlin_version = '1.1.51'
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0-alpha01'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

    }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

I tried several "ways" i found in the internet, but nothing worked. Renaming the file, which is obviously not the Solution, didn´t help. I´ve created a new build.gradle.kts file in my root project but the file isn´t shown in my project. Also gradle didn´t recognize the new file.

So my question is: How can i transform my groovy build.gradle file into a kotlin build.gradle.kts and add this new file into my existing project?

Thanks for your help.

Exitare
  • 561
  • 2
  • 10
  • 30

2 Answers2

31

Of course renaming won't help. You'll need to re-write it using Kotlin DSL. It is similar to Groovy, but with some differences. Read their docs, look at the examples.

In your case, the issues are:

  1. ext.kotlin_version is not valid Kotlin syntax, use square brackets
  2. All Kotlin strings use double quotes
  3. Braces are required around parameters for most function calls (there are exceptions, like infix functions)
  4. Slighlty different task management API. There are different styles available. You can declare all the tasks in tasks block as strings, or use a single typed function, as in the example below.

Take a look at the converted top-level build.gradle.kts:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext["kotlin_version"] = "1.1.51"
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath ("com.android.tools.build:gradle:3.1.0-alpha01")
        classpath ("org.jetbrains.kotlin:kotlin-gradle-plugin:${ext["kotlin_version"]}")
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
}

task<Delete>("clean") {
    delete(rootProject.buildDir)
}
madhead
  • 31,729
  • 16
  • 153
  • 201
  • Thanks for the fast and clear answer. I ´ve implemented the top gradle file and it works well. Thx for that. I´ve read the Docu and had a look at the Samples. – Exitare Nov 07 '17 at 08:57
  • In fact, i don´t get it all. If i try to convert my 2nd file the same way as you "told" to do. there are several errors like "unresolved References" etc. For example: This is my code: android { compileSdkVersion ("28") buildToolsVersion ("27.0.0") } but android and the following is an unknow expression. What is my failure? Is there a docu as well. I´m so sorry for being so dumb. I´m new to this whole area. – Exitare Nov 07 '17 at 09:09
  • 1
    We're here to help. Please, create another question with the issues you have with other file. I guess, most probably you'll need to use `configure {}` (I do not know the class), instead of `android`, but let us see it all. – madhead Nov 07 '17 at 11:19
  • Is there any advantage of switching to .kts? I'm trying to convert my build.gradle now, and I keep stubbing my toe. – Josh C. Aug 08 '19 at 17:23
  • Probably if you're fine with Groovy then there will be no advantage. Kotlin scripts will be even a little bit slower. However, Kotlin scripts provide better IDE support due to static typing. Moreover (that's totally my IMHO): Groovy is loosing its positions and we'll see more Kotlin support and Kotlin-centric features in Gradle in future. – madhead Aug 08 '19 at 19:02
  • I want to point out that there's a [GradleKotlinConverter][1] script to automate some of the more common chores when converting groovy gradle files to kotlin. [1]: https://github.com/bernaferrari/GradleKotlinConverter – Johannes Rudolph Dec 27 '19 at 13:39
0
buildscript {
    extra.apply {
      var  kotlin_version = "1.7.10"
      var  navigationVersion = "2.5.0"
      var  hilt_version = "2.42"
    }

//        .kotlin_version("1.7.10")
//    ext.navigationVersion("2.5.0")
//    ext.hilt_version("2.42")
    repositories {
        gradlePluginPortal()
        google()
        mavenCentral()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:7.2.1")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10")
        classpath("androidx.navigation:navigation-safe-args-gradle-plugin:2.5.0")
        classpath("com.google.firebase:firebase-crashlytics-gradle:2.9.1")
        classpath("com.google.gms:google-services:4.3.13")
        classpath("com.google.firebase:perf-plugin:1.4.1")
        classpath("com.google.dagger:hilt-android-gradle-plugin:2.42")
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    //    classpath("com.google.dagger:hilt-android-gradle-plugin:$extra.hilt_version")
    }
}

allprojects {
    repositories {
        gradlePluginPortal()
        mavenCentral()
        google()
        jcenter()
        maven { url  = uri("https://jitpack.io") }
        maven { url =  uri("https://cdn.veriff.me/android/") }
        flatDir {
            dirs("libs")
        }
    }
}

tasks.register("clean"){
    delete(setOf(rootProject.buildDir))
}




    import extensions.*
    import java.time.LocalDate
    import java.time.format.DateTimeFormatter.*
    
    plugins {
        id(Plugins.ANDROID_APPLICATION)
        id(Plugins.ANDROID)
        id(Plugins.PARCELIZE)
        id(Plugins.KAPT)
        id(Plugins.NAVIGATION_SAFE_ARGS)
        id(Plugins.GOOGLE_SERVICES)
        id(Plugins.CRASH_ANALYTICS)
        id(Plugins.PERFORMANCE_ANALYTICS)
        id(Plugins.DAGGER_HILT)
    }
    
    var applicationName = "abc`enter code here`"
    
    android {
        compileSdk = AndroidConfig.COMPILE_SDK
        bundle {
            language {
                enableSplit = false
            }
        }
    
        defaultConfig {
            configurations.all {
                resolutionStrategy { force(AndroidConfig.FORCE_STRATEGY) }
            }
            applicationId = AndroidConfig.APPLICATION_ID
            minSdkVersion(AndroidConfig.MIN_SDK)
            targetSdkVersion(AndroidConfig.TARGET_SDK)
            versionCode = AndroidConfig.VERSION_CODE
            versionName = AndroidConfig.VERSION_NAME
            testInstrumentationRunner = AndroidConfig.TEST_INSTRUMENTATION_RUNNER
    
            //javaCompileOptions.annotationProcessorOptions.arguments['dagger.hilt.disableModulesHaveInstallInCheck'] = 'true'
        }
    
        applicationVariants.all {
            outputs.all {
                var formattedDate = LocalDate.now()//LocalDate.now().format(ofPattern("yyyy-MM-dd"))
                var outputFileName =
                    "${applicationName}_${buildType.name}_${formattedDate}_v${defaultConfig.versionName}.apk"
            }
        }
    
        buildTypes {
            getByName("debug") {
                // minifyEnabled = "false"
                isMinifyEnabled = false
                isTestCoverageEnabled = true
                isShrinkResources = false
                isDebuggable = true
                proguardFiles(getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro")
                testProguardFiles(getDefaultProguardFile("proguard-android.txt"),
                    "proguardTest-rules.pro")
    //            FirebasePerformance {
    //                // Set this flag to 'false' to disable @AddTrace annotation processing and
    //                // automatic HTTP/S network request monitoring
    //                // for a specific build variant at compile time.
    //                isInstrumentationEnabled = true
    //            }
            }
    
            getByName("release") {
                isMinifyEnabled = false
                isShrinkResources = false
                proguardFiles(getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro")
                testProguardFiles(getDefaultProguardFile("proguard-android.txt"),
                    "proguardTest-rules.pro")
            }
        }
    
        buildFeatures {
            viewBinding = true
            dataBinding = true
        }
    
    //    compileOptions {
    //        sourceCompatibility = JavaVersion.VERSION_11
    //        targetCompatibility = JavaVersion.VERSION_11
    //    }
    
        compileOptions {
            sourceCompatibility = JavaVersion.VERSION_1_8
            targetCompatibility = JavaVersion.VERSION_1_8
        }
        kotlinOptions {
            jvmTarget = JavaVersion.VERSION_11.toString()
            //freeCompilerArgs= ["-Xjvm-default=compatibility"]
            freeCompilerArgs = listOf("-Xjvm-default=compatibility")
            // freecompilerargs = List( -Xjvm-default=compatibility)
        }
        flavorDimensions("mode")
    
        productFlavors {
            maybeCreate("Staging")
            maybeCreate("PreProduction")
            maybeCreate("Production")
            getByName("Staging") {
                applicationIdSuffix = ".staging"
                //versionNameSuffix = ".staging"
                
            }
            getByName("Production") {
                dimension = "mode"
                resValue("string", "app_name", "abc")
               
            }
        }
        packagingOptions {
            resources.excludes += "META-INF/DEPENDENCIES"
            resources.excludes += "META-INF/NOTICE"
            resources.excludes += "META-INF/LICENSE"
            resources.excludes += "META-INF/LICENSE.txt"
            resources.excludes += "META-INF/NOTICE.txt"
    
            //   excludes += ['META-INF/DEPENDENCIES', 'META-INF/NOTICE', 'META-INF/LICENSE', 'META-INF/LICENSE.txt', 'META-INF/NOTICE.txt']
    
        }
        dynamicFeatures += setOf(":BuyCryptoModule",":"points")
    
    }
    
    dependencies {
        //includeing file libs
        val daggerVersion = "2.42"
        implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar"))))
        implementation(files("geetest_captcha_android_v1.7.1.1_20220308"))
        appModuleDeps()
        kaptAndroidTest("com.google.dagger:hilt-compiler:2.42")
        // For local unit tests
        testImplementation("com.google.dagger:hilt-android-testing:2.42")
        kaptTest("com.google.dagger:hilt-compiler:2.42")
        implementation(files("libs/opencsv-5.2.jar"))
        kaptAndroidTest("com.google.dagger:dagger-compiler:$daggerVersion")
        kaptTest("com.google.dagger:dagger-compiler:$daggerVersion")
        releaseImplementation("com.github.ChuckerTeam.Chucker:library-no-op:3.5.2")
    }
    kapt {
        correctErrorTypes = true
    
            arguments {
                // Make Hilt share the same definition of Components in tests instead of
                // creating a new set of Components per test class.
                arg("dagger.hilt.shareTestComponents", "true")
            }
    
    }
Mohammad Muddasir
  • 947
  • 10
  • 21