Kotlin Help

Hello world

Here is a simple program that prints "Hello, world!":

fun main() { println("Hello, world!") // Hello, world! }

In Kotlin:

  • fun is used to declare a function

  • The main() function is where your program starts from

  • The body of a function is written within curly braces {}

  • println() and print() functions print their arguments to standard output

A function is a set of instructions that performs a specific task. Once you create a function, you can use it whenever you need to perform that task, without having to write the instructions all over again. Functions are discussed in more detail in a couple of chapters. Until then, all examples use the main() function.

Variables

All programs need to be able to store data, and variables help you to do just that. In Kotlin, you can declare:

  • Read-only variables with val

  • Mutable variables with var

To assign a value, use the assignment operator =.

For example:

fun main() { //sampleStart val popcorn = 5 // There are 5 boxes of popcorn val hotdog = 7 // There are 7 hotdogs var customers = 10 // There are 10 customers in the queue // Some customers leave the queue customers = 8 println(customers) // 8 //sampleEnd }

As customers is a mutable variable, its value can be reassigned after declaration.

String templates

It's useful to know how to print the contents of variables to standard output. You can do this with string templates. You can use template expressions to access data stored in variables and other objects, and convert them into strings. A string value is a sequence of characters in double quotes ". Template expressions always start with a dollar sign $.

To evaluate a piece of code in a template expression, place the code within curly braces {} after the dollar sign $.

For example:

fun main() { //sampleStart val customers = 10 println("There are $customers customers") // There are 10 customers println("There are ${customers + 1} customers") // There are 11 customers //sampleEnd }

For more information, see String templates.

You will notice that there aren't any types declared for variables. Kotlin has inferred the type itself: Int. This tour explains the different Kotlin basic types and how to declare them in the next chapter.

Practice

Exercise

Complete the code to make the program print "Mary is 20 years old" to standard output:

fun main() { val name = "Mary" val age = 20 // Write your code here }
fun main() { val name = "Mary" val age = 20 println("$name is $age years old") }

Next step

Basic types

Last modified: 25 September 2024