Search code examples
javakotlincordova-plugins

How to add Android Kotlin files to a Cordova Plugin project


Is it possible to add Android Kotlin files to a Cordova Plugin project or is only Java supported?

<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
        version="0.0.1">

  <!-- android -->
  <platform name="android">

    <source-file src="src/android/nl/companyname/kotlin/ScanMode.kt" target-dir="src/nl/companyname/kotlin"/>

  </platform>

</plugin>

The Java files show up, but the Kotlin files don't. I also don't see any plugin that has it.


Solution

  • add the following in config.xml

    <preference name="GradlePluginKotlinEnabled" value="true" />
    <preference name="GradlePluginKotlinCodeStyle" value="official" />
    <preference name="GradlePluginKotlinVersion" value="1.3.50" />
    

    also note where to put the kotlin files, i.e. src/main/kotlin///

    using:

    <source-file src="src/android/file.kt" target-dir="app/src/main/kotlin/xx/yy/zz" />
    

    and add the below to your plugin's gradle.build if the kotlin files aren't picked up by your project

    android {
        sourceSets {
            main.java {
                srcDirs += 'src/main/kotlin'
            }
        }
    }
    

    This answer is referenced from: https://stackoverflow.com/a/63872580/10999673

    I modifed an example repository to test this:

    https://github.com/kilisio/cordova-plugin-hello-kotlin.git