After getting a light idea of what Kotlin is and what it can do for us, it´s time to configure Android Studio to help us develop Android apps using Kotlin. It requires some steps that only need to be done first time, but some other Gradle configurations will need to be done on every new project.
For this set of articles, I´ll be creating a reduced version of Bandhook, an app I created some time ago, which will basically connect to a music rest API and return some info about a set of bands. Go to Bandhook Kotlin on Github and take a look at the code.
Create a new project and download Kotlin plugin
Just create a basic Android project with an activity using Android Studio, the same way you would do for a regular project.
Once done, first thing you´ll need is to download Kotling plugin. Go to Android Studio preferences and search plugins. Once there, use search again to find Kotlin plugin. Install and restart the IDE.
Add Kotlin plugin dependency to your application build.gradle
The root build.gradle needs a new dependency that will be required to use the Kotlin plugin in our main module:
[groovy]
buildscript {
repositories {
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:1.5.0"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.0.1"
}
}
[/groovy]
Configure module build.grade
First, apply Kotlin plugin:
[groovy]
apply plugin: ‘com.android.application’
apply plugin: ‘kotlin-android’
[/groovy]
Then, add the Kotlin library to your dependencies:
[groovy]
dependencies {
compile fileTree(dir: ‘libs’, include: [‘*.jar’])
compile ‘org.jetbrains.kotlin:kotlin-stdlib:1.0.1’
}
[/groovy]
That should be all. However, if your project is mixing both Java and Kotlin files, I recommend you to create a folder for Kotlin sources:
[groovy]
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
…
sourceSets {
main.java.srcDirs += ‘src/main/kotlin’
}
}
[/groovy]
Alternatively, you can skip this step, and after doing next ones, use this Android Studio action:
I prefer doing it manually to keep my Gradle files organized, but this second option could be easier.
Create Kotlin folder
You can skip this point if you don’t mix Java and Kotlin files. Creating the folder will be easier if you change the project visualization from ‘Android’ to ‘Project’. Go to ‘app->src->main’ and create a folder called ‘kotlin’:
Convert java activity to a kotlin file
Kotlin plugin can convert from Java to Kotlin classes. We can convert our current activity to a Kotlin class very easily from ‘Code’ menu, by choosing ‘Convert Java File to Kotlin File’:
IDE will suggest to move new file to the Kotlin folder. Click on ‘Move File’ (or move it manually if you don´t see the option).
You will get a very similar code translated to Kotlin. I suggest taking a look until you understand the differences:
[kotlin]
class MainActivity : ActionBarActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.getItemId()
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true
}
return super.onOptionsItemSelected(item)
}
}
[/kotlin]
Main differences
Just taking a look at previous code, we can see some direct differences. There are many more we´ll be discovering in next posts:
- Use of colon instead of the word ‘extends’
- Explicit use of ‘override’: in Java, we can use an annotation to make our code more clear, but it´s not a condition. Kotlin will force us use it.
- Use of ‘fun’ for functions: Kotlin is and object-oriented functional language, so it will be very similar to other languages such as Scala. Java methods are represented as functions.
- Function parameters use a different nomenclature: Type and name are written the other way round and separated by a colon
- Optional use of semicolons: we don´t need to finish our lines with a semicolon. We can if we want to, but it can save a lot of time and make our code cleaner if we don´t do it.
- Other small details: In introductory article, I already talked about the ‘?’ symbol on. This indicates the parameter can be null. Nullity is handled different from what we are used in Java
Conclusion
Though we can think using a new language will be very difficult, Kotlin is being created by the JetBrains team to be the most easy and interoperable language to cover the needs Java lacks. As Android Studio is also based on a JetBrains product, it will be very easy to integrate to this IDE and start working with it.
Next article will cover some tips and tricks to make our life easier when developing Android apps with Kotlin.
Since M11 you can keep Kotlin files in java folder. However, I prefer keeping them separated in kotlin folder.
Thanks! Didn’t know, but I also think it’s better to keep them separately.
Marvellous tutorial to start development in Android using Kotlin language. Keep posting new features related to Kotlin.Great !!!
Thanks for the article.
I’m trying to learn about the clean architecture and kotlin by reading your codes.
And creating an app using this architecture, one of the component is authorisation using OAuth2.
Where should i put this component? Inside repository or other module?
The component also handle the access token refresh if possible.
Thanks for your blog. I am just introducing with Kotlin. And I would like to use kotlinx library (extension for Android) and I add into gradle file but when I run the project compiler could not finish success because it did not find kotlinx 🙁 What should I modify or add to the project ?
That happened to me when I tried to add kotlinx to main build.gradle instead of app module build.gradle. Not sure why is that, but it’s a bit annoying having to declare plugin dependencies there.
First – thanks for Your book. Unfortunately, I have a big problem with Kotlin and Anko. When I was usin Kotlin in version 0.14.449 without Anko, for app with min sdk 16, everything was fine. But, after updating to version 1.0.0-beta-1038 Android Studio stoped installing app for Android lower than 5.0 – it complains about “INSTALL_FAILED_DEXOPT”. Also, with Kotlin 0.14.449 with Anko it’s the same. Only Kotlin 0.14.449 without Anko works for me for Android lower than 5.0. Cleaning project doesn’t help. Do You have such problems or you know what’s going on?
Yeah, they introduced a bug in the beta candidate. https://youtrack.jetbrains.com/oauth?state=%2Fissue%2FKT-9737
It should be solved in beta-1103, but I also reproduced there. It seems you need to delete the folder data/data/packagename
I tried, including wiping virtual device (android emulator, Genymotion), creating new devices – nothing helped. So – I have to wait for new Kotlin version?
Not sure tbh… I’d suggest you to join the oficial slack (kotlinlang.slack.com) and ask the Kotlin team directly.
The actual version is org.jetbrains.kotlin:kotlin-gradle-plugin:1.0.0-rc-1036. Theres a release canditate for kotlin 1.0! this is great!
Yeah! Hope to find some time to update all the articles.