Hello world
Here is a simple program that prints "Hello, world!":
In Kotlin:
fun
is used to declare a functionThe
main()
function is where your program starts fromThe body of a function is written within curly braces
{}
println()
andprint()
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:
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:
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: