This video Explore Kotlin Language Basics was last updated on Aug 9 2022
If you built the bullseye game in your first koltin android app course, then you’re already familiar with some kotlin syntax and concepts. This episode will serve a basic introduction to explore the kotlin language if you’re new to kotlin. And a refresher if you watched the first kotlin android app course.
So let’s get started.
First let’s explore naming data and data types. Variables are used to store data in a program. Let’s say you want to store a person’s age. You store it in a variable.
You’ll add some code inside the main function.
I’ll declare a variable named age
, which is of the type Int
, and is equal to 32
.
var age: Int = 32
In here, you declared a variable named age
and assigned the value 32 to it.
So the age variable stores the value 32.
We also gave it an Integer data type.
Int is used to store whole numbers.
We use the var
keyword in the variable definition because we want to let kotlin know that this variable can change.
So the age next year would be 33.
So using var
makes it possible for you to reassign the age to a new value.
Do note I mentioned that var is a keyword. Keywords in programming are just sets of reserved words used internally by the programming language. They are reserved words so for instance you can’t name your variable with the word var.
Now speaking of keywords, we have another one we can use to denote data called val
.
And no this is not the short form for Valentine :]
Enter the following code to store a name:
val name: String = "Ayo"
This time around we use the val
keyword, to make it a constant, meaning you can’t change it,
and it will represent the person’s name.
This makes sense because a person’s name would always remain the same every year.
A good technique is to define everything using val
and only change it to var
if the compiler complains!
Also, notice that we use a different data typed called String
.
Strings are used to store a collection of characters in this case a text.
Do note that the text must be wrapped in double quotes.
If you use single quote then it becomes a character and you’ll have to change the datatype to Char
and you must pass in only one character as its name suggests.
To print out the name using the println()
function, pass it in as an argument like so:
println(name)
Run the project, by pressing the green arrow in the toolbar above. You should see the name in the run panel below.
You might notice how the editor has grayed out the types here. This is because Kotlin can infer the type based on the values passed to it in the declaration, and as such, you don’t always have to explicitly mention them. This is called “type inference.”
Let’s add a third value here, named lastName
.
Once again, use a val
, but this time, don’t add the type, just set it to Balogun
.
val lastName = "Balogun"
You can see that even though you haven’t mentioned the type, the compiler can recognize it’s a String.
Kotlin also supports types other than String
and Int
, so define another constant named weight
, and set it to 80.1
.
That’s kind of my average weight at the moment but let’s just assume that Ayo weighs the same.
val weight = 80.1
Because you used a decimal point (.
), the type of the value is a Double
.
Now, instead of just printing the values, you can add extra text to them, or even interpolate them into another String
.
Let’s see what that means.
Add another println()
call, and put in the following description:
println("$name is a musician")
You’re printing out the message “Ayo is a musician”, where name
will be replaced with the value from the variable.
This happens when a string contains embedded expression denoted with the dollar sign.
And it is called String
templates or String
interpolation in some other programming languages.
And by the way, Ayo Balogun is an Afrobeats musician popularly known as Wizkid.
Run the project, to see the string printed out.
Cool!!!
Now, you remember how age
is a variable, right?
This means you can change it.
Let’s say a year passes, and Ayo ages a little more.
To add a year to age
, you can use the +=
operator, which uses the current value to add a number,
and then reassigns the age
variable.
Add in the code like so:
age += 1
Then add a print statement before and after the age increment.
println(age)
age += 1
println(age)
Run the project, to see the change in the age.
String templates are really useful, and you can use it to interpolate more than one value in a String
,
or even to create values for your variables or constants.
Instead of printing out each value independently, you can format them in one String
, and print it all out, in one go.
Add the following code to your project:
println("$name $lastName is $age years old, and weighs $weight kg")
Run the project, to see the values nicely formatted.
As mentioned, you can use string templates to assign values to variables and constants.
Let’s do that by creating a constant named fullName
and print it out.
Enter the following code:
val fullName = "$lastName, $name"
println(fullName)
Run the project, and you should see the fullName
.
Values are not there just for assinging and printing out.
They can be transformed from one type to another, like from a number to a String
, or from a String
, to a number.
This type of conversion is necessary when doing some type of computation.
Let’s see how to do that. Paste in the following code:
val ageAsString = age.toString()
println(ageAsString)
val ageFromString = "35".toInt()
println(ageFromString)
val nameLength = fullName.length
println(nameLength)
In the first part you’re converting the age value to a String
, and in the second,
you’re doing a reverse operation, by converting a String
to an Integer.
The last example takes the fullName
String
, and assigns its length to a constant.
length
is a property of the String class and it returns the number of characters in a string.
Run the project, to see the values printed out accordingly.
The final basic concept you will use in your code is the process of commenting code. Comments are different from pieces of code in that they aren’t executed. Instead they serve to help developers understand what a piece of code does, to showcase example usage, or even as official documentation for some features in your code.
Let’s add a few comments to your code.
The most basic comment is the line comment. You add a line comment like so:
// This is a line comment
You will see how the comment and the line is grayed out.
You can also add a single line comment by clicking on the line or selecting the lines of code you want to comment out
then press Cmd + /
.
You can then uncomment it by pressing Cmd + /
once again.
You also have the multi-line comments if you need to explain things in detail. Add it in like so:
/* This is a multiline comment.
You don't have to add // before
each line.
*/
They start with a /*
and end with a */
.
You can see that you can also nest comments within other comments for further clarification.
The last type of comments is the Kotlin or Java Doc comment type. Doc stands for documentation, and it’s used just for that.
Let’s scroll to the top of the main()
function and write a small documentation comment.
To open up documentation comments, enter down the following:
/***/
The distinction between these comments and a regular multi-line one is that this one has two asterix (*
) after the first slash.
You can also see that the comments are green instead of gray.
This is to make them more noticable, as they are documentation after all.
Tap Enter a few times to add new lines, after the second *
.
The real power of these comments is the ability to reference things.
Add the following text to the comments:
/**
* This is a documentation-style comment.
* You can reference things here, like the [main] function.
* You can reference parameters, like the [arguments].
* String arguments passed through the run panel as [arguments].
* */
You can see that you can reference the main function for example, or any other function in the project. If you click on the reference, it will highlight the function within the file. You can also hold down Command + Click on it or Control + Click on windows, to jump to the definition.
Notice the line where you referenced the arguments
.
There are no parameters within this function, so it doesn’t lead to anywhere, but let’s add a parameter
to the main()
function as follows:
fun main(arguments: Array<String>) ...
Every main function can receive String
arguments from the run panel if you’re running it through the run panel client.
If you go back to the arguments
reference, you can see that they are highlighted.
These type of comments are used internally in Kotlin to explain functions and other code that kotlin provides. You just hover over a function or class and the documentation comments are displayed with the necessary information you need.
These are the basics of the Kotlin programming language, it’s time to proceed through the rest of the course! See you in the next episode! :]