Scratching your way out in Android Studio with Scratch files

Prafull Mishra
3 min readJan 2, 2020
scratches everywhere

We all have been there, when we wanted to write a small piece of code to see if it solved a particular problem statement. Say you want a Kotlin function that returns the largest Ship from a fleet.

If you are working in a Kotlin-only environment/IDE, you can easily just write a sample function and call it in the main() will do fine. It might take a few seconds and then the output will be in front of your eyes.

But what if you are working on an Android project? In that case you will have to wait for the whole app to build and get deployed. Even worse, if the project is humongous, it definitely will take more than a few seconds to get to see if your code worked or not. That too multiplied by the number of times you need to change the code to perfection and you are seeing well beyond an hour just to make a small working piece of code…

Fortunately, JetBrains thought of it and aptly named the feature — Scratch files!

Yes you heard it right. As the name suggests, Scratch files lets you quickly create a separate small piece of code, that can run independently of the project, and if you want can include modules from the app too! And the biggest benefit, you don’t need to build your whole project to run it!!

Enough hype, time for the show

To create a scratch file :

  • From the File menu, select New, and then click Scratch File (or just press ⇧⌘N on Mac OS)
  • Select the language option that you want to write code of

Let’s assume the selected language as Kotlin for our case.

scratch files in action
Code on left, result on right — with Interactive mode enabled

If you look closely, few interesting things can be noted instantly:

  • A.S. generates a file with name of format → scratch_<count>.kts
  • Since this is the first scratch file I generated in this project, it was named scratch.kts, but any subsequent files will be named as scratch_1.kts, scratch_2.kts and so on
  • Enabling the Interactive Mode checkbox, will display the result of the written code simultaneously
  • If you want to access code from some module, you can use the drop down to select the specific module which you want to include
  • The ▶ button at top left will execute the scratch code (might not be needed if you have Interactive mode enabled)

To locate your scratch files later, change the view type to Project, and then open Scratch and Consoles > Scratches. For more details, see this link.

With this handy tool, you no longer need to interfere with project file structure, as these scratch files remain outside of your project’s context. Giving you the freedom to experiment with your code without any hesitation.

👏 This is my first blog on Medium. Do clap if you found this useful! 👏

--

--