Play with Variables in Kotlin

Vish Katyan
2 min readJun 28, 2023

--

Kotlin Programming Langauge

If you haven’t read my previous post for Write Your First Line of Code in Kotlin, read it now. Now, let’s understand how to create variables in kotlin Programming Language.

To Run your Line of Code in a browser-based programming tool, click on the link https://developer.android.com/training/kotlinplayground?authuser=1

fun main()
{
println("Happy Birthday Vish")
println("You're already 21")
}

First, run above LOC and see what happens. This code prints the output as:

Happy Birthday Vish
You're already 21

Instead of writing and repeating the number, name, etc… you could store it in a container and assign some name to it so that it can be easily accessible whenever needed.

Create a Variable in Kotlin

val age = 21

Let’s understand the above LOC

Add the above code to your main() function.

  1. val → This is a special word used in kotlin language or called a keyword that tells there is a variable name next to it.
  2. age → This is the name of the variable (a container in which value is stored).
  3. = → This is an assignment Operator that works right to left.
  4. 21 → It is the value assigned to the variable age.

Note :

Variables declared with val can only be set once, and can’t be edited later. Variables declared with var can be edited later.

How to Print Variables

To print the variables declared with val, a dollar sign is used surrounded by curly braces. It is shown as:

${variable}

If I need to print the above age variable, then the code must be shown as:

fun main()
{
println("You're already ${age}")
}

Unlike Java, you don’t have to declare the type of variables while creating.

Print the name using variable

fun main()
{
val name = "Vish"
println("${name}")
}

Your full code should look similar to this and output will be the same.

fun main()
{
val age = 21
val name = "Vish"
println("Happy Birthday ${name}")
println("You're already ${age}")
}

Congratulations, you’ve learned about variables in kotlin programming language. Hope you’ll like it. You can also Buy Me A Coffee.

Thank You :)

--

--

Vish Katyan

Hi I am Vishakha, a blogger, content creator and a developer.