简体   繁体   中英

Apply Kotlin multiplatform plugin via gradle legacy plugin application

I'm doing some in-depth hands-on with Kotlin Multiplatform Mobile and I'm forced to apply Gradle plugins with the legacy way of applying plugins.

I'm using Kotlin DSL for Gradle and I didn't manage to include the kotlin-multiplatform plugin.

Essentially, there are two ways to include a gradle plugin in your project:

  1. via Gradle Plugins DSL (a modern way)
  2. via legacy plugin application (deprecated but more flexible).

I've basically created a very blank gradle project ( gradle init ), not related to any IDE or any other dependencies, which both are common for KMM projects - to isolate the issue as much as possible.

The build.gradle.kts below works just fine, when run via ./gradlew clean build (via Plugins DSL)

plugins {
    id("org.jetbrains.kotlin.multiplatform") version "1.4.10"
}
kotlin {
    jvm()    
}
repositories {
    jcenter()
}

However, this won't work (via legacy plugin application):

buildscript {
  repositories {
    maven {
      url = uri("https://plugins.gradle.org/m2/")
    }
  }
  dependencies {
    classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.10")
  }
}
apply(plugin = "org.jetbrains.kotlin.multiplatform")
kotlin {
    jvm()    
}
repositories {
    jcenter()
}

It fails with this error:

* What went wrong:
Script compilation errors:

  Line 12: kotlin {
           ^ Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
               public fun DependencyHandler.kotlin(module: String, version: String? = ...): Any defined in org.gradle.kotlin.dsl
               public fun PluginDependenciesSpec.kotlin(module: String): PluginDependencySpec defined in org.gradle.kotlin.dsl

  Line 13:     jvm()
               ^ Unresolved reference: jvm

2 errors

It can't resolve the kotlin {} block which is essentially the entry point in KMM projects.

Interestingly, using Groovy instead of Kotlin for Gradle - works in both cases.

But I would like to use Kotlin DSL for Gradle and apply the plugins via the legacy way, since this way I can apply plugins dynamically, ie under certain conditions.

In general, you can use apply false in the plugins DSL and call apply conditionally. Apply alone will NEVER work with Kotlin DSL, it only works with dynamic Groovy. Kotlin can work like Groovy if you also use the plugins DSL + apply false in it. Example:

plugins {
    kotlin("multiplatform") apply false // Applied conditionally later
}

For more detailed discussion of the problem check this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM