Meet the Kotlin Programming Language

Apr 10 2024 · Kotlin 1.9, Android 14, Android Studio Hedgehog

Lesson 01: Getting Started with Kotlin

Demo

Episode complete

Play next episode

Next
Transcript

In this module, you won’t write any code for an app, instead, you’ll use a handy feature available in Android Studio and IntelliJ IDEA called Scratch Files to experiment and prototype with Kotlin code quickly.

Open the Starter project in the 01-getting-started-with-kotlin directory of the m3-kpl-materials repo in Android Studio Hedgehog or later.

Wait for the project to build.

To create a scratch file, right-click on the com.yourcompany.android.meetkotlin package, select New and then click Scratch File.

In the pop-up that opens, select Kotlin.

Once you do, a new scratch file will open. The left pane is where you’ll write your code, and the right pane will show you the output as you write.

Make sure Interactive Mode is checked. This runs your code automatically once you stop typing.

Your environment is now set up.

As is customary with any programming tutorial introduction, you’ll start with a simple program that displays the text Hello World on the screen.

Type the following in the editor:

println("Hello World!")

Once you type the line, you’ll notice the output on the right panel, as shown below.

println() is used to print its argument, i.e., the stuff between the () to the console on a new line.

Now that you know how to print a message to the console, it’s time to work with variables.

Enter the following snippet in your scratch file.

val country = "India"
println("Greetings from $country!")

In the snippet above you:

  • Created an immutable variable called country and assigned it a value of `India’.
  • You then used the println() to print out a greeting that uses the country variable.

Note: The $ sign holds a special meaning in Kotlin. When used inside double quotes with the name of a variable, it uses the variable’s value.

Since country is an immutable variable, reassigning it will result in an error. Try it out by pasting the following snippet below the println():

country = "Singapore"
println("Greetings from $country!")

You’ll notice a red squiggly line on the line where you are reassigning the country variable. It’s complaining because you’re trying to reassign a val variable. This isn’t allowed in Kotlin.

In cases where your variable’s value needs to change, you need to use var.

The var keyword tells the Kotlin compiler that the variable’s value can be reassigned or changed later.

Fix the error by changing country from val to var, and you’ll notice the output printing the new greeting.

That ends this demo. Continue with the lesson for a summary.

See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion