Faster Backend Development: Running 'Raw' Kotlin in Android Studio
A Step-by-step Guide with Images
Starting out in Android programming, most of what you do will be related to getting things to show up on the screen. As your projects get more complex, you may find that your backend code is taking up a lot more of your time and focus.
Advantages of Running Raw Kotlin
- Faster build times: Skip the heavy Gradle build process required for Android dexing.
- Quicker prototyping: Rapidly iterate on algorithms or data structures.
- Easier testing: Test logic in isolation without needing an emulator or device.
- Better architecture: Naturally forces a separation of concerns between logic and UI.
Is It Complicated?
No, it's really easy to add a module to an existing project or make a specific project just for running raw Kotlin. I've done both of these in the past and both work well.
I've added a lot of images to this guide to make this as beginner-friendly as possible.
Alright, Let's Go!
Next, we need to add a new Java / Kotlin Library Module to our project. Simply go to File->New->New Module...
Now edit the Main.kt and add the entry point using @JvmStatic fun main(args: Array<String>). This is essential for everything to work correctly and is the most common point of failure.
Add a new configuration - Application:
This is the next most likely place you will go wrong. In Build and run, you need to add the following settings:
- Add a Name so you can identify the configuration. I'm using RawKotlin.
- Select the Java version (I'm using 21 here)
- Select your main branch from the Library Name that you added (main is lower case here)
- Select the Main file you just edited with the @JvmStatic entry point using the browse icon on the right (see second image for selection interface)
After hitting OK, you should now have your RawKotlin (or whatever name you gave the configuration) selected. Hit the run button on the right of that. At the bottom, you should now see everything build then run.
Completed!
Congratulations! You can now run Kotlin code in a terminal without the overhead of an Android emulator. You’ll likely notice significantly faster build times immediately.
Bonus: Accessing Your Kotlin Module from the App
Import the Module
Create a Test File
Add a new object in your RawKotlinCode module called RawKotlinTest and give it a string value called NAME (all uppercase as we have made this a const value):
Access it from your App
Open up your MainActivity.kt from your app. Change the name to name = RawKotlinTest.NAME.
Change the run configuration back to app and run the app.
All Done!
That's pretty much it.
If you are new, I would recommend practicing making some Raw Kotlin files and accessing them from the Main file. Change between the app and RawKotlin configuration a few times to ensure you remember how to do it. You may also want to add new Raw Kotlin modules.
Comments
Post a Comment