Start learning free

LESSON 10 OF 414 · VARIABLES

Data Types in Kotlin

Lesson

TL ; DR:

In Kotlin, not all data is treated the same. There are different data types, such as:

  • Int - represents integer numbers like 3 and -12

  • Double - represents floating point numbers like 3.14

  • String - represents a string (sequence of characters) like "John Doe"

  • Boolean - represents data that can have one of two values: true or false

  • Char - represents a single character like 'a', 'Z' or '?'



Full lesson:

One instruction can have several distinct meanings depending on the data types it's working with.

For example, suppose you see this line of code somewhere in a program:

println(a + b)

Can you tell for sure what it does without knowing anything about the variables a and b?

It might add two numbers, if a and b are both numbers:

val a = 10
val b = -5

println(a + b) // Output: 5

But it also might concatenate two strings, if a and b are both strings:

val a = "Hello "
val b = "world!"

println(a + b) // Output: Hello world!

Of course, addition and string concatenation are two completely different operations and Kotlin needs to figure out which one to do.

And this is exactly why Kotlin assesses the data type of every value you use in your program. In order to be able to make these decisions when needed.

In our example, when it reads a + b, Kotlin checks the data type of a and b. If both are strings, it performs string concatenation. If both are numbers, it performs addition.


Invalid operations:

Asessing data types is also helpful for Kotlin to make sure that what you do with the data actually makes sense.

For example, computers can perform mathematical operations on numbers, but not on strings. Of course, nobody can stop you from writing a program like this:

val a = "peanut"
val b = "butter"

println(a * b) // compile error

But when you try to run this program, Kotlin will refuse to compile it and report error: unresolved reference 'times' for operator '*'.

This is the way of Kotlin telling you: "Hey, I'm a little confused. How do you multiply two strings? I've never heard of that."


Nullability:

By default a Kotlin type can never hold null. To allow a missing value, add a ? to the type — String? means "a String, or null". To read a nullable value safely, use the safe call ?. (it yields null instead of crashing); use !! only when you are certain the value is non-null.

val name: String? = null // allowed because of the ?
println(name?.length)    // safe call, prints null
println(name!!.length)   // asserts non-null, throws NullPointerException if null

Assignment
Follow the Coding Tutorial and let's practice with data types!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check