“Start using Kotlin” guide for Android Developers
Hello, dear reader. I hope you heard about Kotlin — JVM Programming Language from JetBrains.
@JakeWharton published document about Kotlin this week and huge amount of developers now want to try Kotlin in their Android apps. Here is lightweight guide for beginners (Gradle + IDEA based IDE).
- Create new branch in your VCS
- Kotlin maintainers created Gradle plugin for Kotlin, let’s add it
Open root build.gradle and add Kotlin Gradle plugin as dependency to the buildscript.dependencies closure
I’m not using “+” in dependencies for build stability, Please visit http://search.maven.org or https://bintray.com to find newest versions of dependencies.
3. Now let’s apply Kotlin Gradle plugin to our Android app module
Open app’s build.gradle (usually -> app/build.gradle) and add to beginning
apply plugin: 'kotlin-android'
4. Kotlin provides Standard Library (STD) as jar package, so let’s add it to dependencies in app’s build.gradle
dependencies { // Kotlin STD Library
compile 'org.jetbrains.kotlin:kotlin-stdlib:0.10.195'}
5. Almost done, now we should declare Kotlin sources directory for Android Gradle Plugin, app’s build.gradle
android { sourceSets { main.java.srcDirs += 'src/main/kotlin'
}
}
Final version of app’s build.gradle
6. The last thing before starting to code something in Kotlin is IDE Support, I hope you use Android Studio or IDEA, Kotlin maintainers (internal team in JetBrains) created IDEA plugin for Kotlin, so let’s install it
Open IDE (IDEA or Android Studio) -> Preferences -> Plugins -> Browse repositories -> Search: Kotlin -> Install Kotlin plugin from JetBrains -> Restard the IDE.
That’s all.
Now let’s code smthg in Kotlin.
- Sync Gradle configuration in IDE
- Create folder for Kotlin code : src/main/kotlin
- Let’s add new package in src/main/kotlin -> “nice.is.kotlin” (Yoda)
- New -> Kotlin file -> HelloKotlinOnAndroid.kt
And you can use it in your Java code:
import nice.is.kotlin.HelloKotlinOnAndroid//
new HelloKotlinOnAndroid().yo(context, "Kotlin, you are running on Android!");
Or better to write everything you can in Kotlin.
What to read?
- “Using Project Kotlin on Android” from @JakeWharton
- Kotlin official website http://kotlinlang.org
- Kotlin documentation http://kotlinlang.org/docs/reference/
Please read exactly in this order, you’ll understand Java’s problems, Kotlin’s solutions and see usage examples.