Introduction
In this article, I will talk about Functions. A quiz will be included at the end of the article, as this will give you an indication of whether or not you have absorbed the concepts covered here. As I said before, You don't have to memorise the syntax, as you can check for any cheat sheets. Just to let you know, I am following the curriculum and content of the google Udacity course, Kotlin Bootcamp for programmers. This course is intended for intermediate to advance programmers, So I am trying to make it a beginner friendly one. As I was kinda suffering when I was taking it.
To practice Kotlin
- Open Android studio
- Choose a new Empty Activity > Next > Name the project > Choose Kotlin Language > Finish
- Click on tools > Kotlin > Kotlin REPL
- The REPL will appear in the window's bottom
- Press Ctrl + Enter to execute any code
Main Function in Kotlin
I have covered how to write a function in Kotlin in this Article.
To run a kotlin program, instead of using the interpreter or the repl, we need a main function as it is the first thing to be executed. We open a new kotlin file class and its extension is .kt in Android Studio or IntelliJ IDEA. Every kotlin function return something and when nothing is specified, it returns "unit", which mean no value. We write a main function as follows:
// Calling a print line function from main function where it takes an array of strings as its argument
fun main (args: Array<String>){
println("What is your name?")
}
Then click on the green run button next to fun main, the run log window will open on the bottom and the output will be as follows:
What is your name?
Main function's arguments in Kotlin
To run a main function with arguments, Click on run > Edit Configurations > write the argument value inside the Program arguments box; I wrote "World".
// Calling a print line function from main function with arguments and using a string template
// We get the first element of args which is "World"
// We use $ and {} for an expression
fun main (args: Array<String>){
println("Hello, ${args[0]}!")
}
Then click on the green run button next to fun main, the run tab will open on the buttom and the output will be as follows:
Hello, World
But what is a string template?
String Templates in Kotlin
A string template is a string that contains a template expression. This template expression starts with a $ "dollar sign" and is either a variable name or an expression enclosed in a {} "curly braces".
//A variable num with value 20
fun main (args: Array<String>){
val num = 20
println("number = $num")
}
//The output
number = 20
//A variable name with value Leila
fun main (args: Array<String>){
val name = "Leila"
println("My name is ${name.length} letters")
}
//The output
My name is 5 letters
In Kotlin, everything has a value
Even if it is just "unit".
we can use the value of "if condition" right away which means:
//The value of isPass will be true or false depending on the grade, and in one line
fun main (args: Array<String>){
val grade = 85
val isPass = if (grade > 50 ) true else false
println(isPass)
}
//It can be shorter as well as follows
fun main (args: Array<String>){
val grade = 85
val isPass = grade > 50
println(isPass)
}
//The output will be:
true
We can use the if condition in a string template as well.
fun main (args: Array<String>){
val grade = 85
val report = "you ${if(grade>50) "passed" else "failed"}!"
println(report)
}
//The output will be
you passed!
Random Java library
Kotlin works with Java libraries for example, Random. As the name suggests, it is for random values.
//Click Alt + Enter to import the java library
import java.util.*
// For candyType function, we have a list of four types of candy & we return a random type using Random. 4 is the upper bound. so it will return any number between 0 & 3.
//For the primary function, we have a variable candy which value is the
function candyType, which will be any string of the four in the available
list.
import java.util.*
fun main (args: Array<String>){
val candy = candyType()
println(candy)
}
fun candyType(): String {
val candy = listOf("Toffee", "caramels", "gummies", "chocolate")return candy[Random().nextInt(4)]
}
Remainder in Kotlin
We use "rem" property, to calculate the remainder when we divide two values as follows:
fun main (args: Array<String>){
val number = 89
val secondNumber = 3
val remainder = number.rem(secondNumber)
val remainderOperator = number % secondNumber
println(remainder)
println(remainderOperator)
}
//The output
2
2
Quiz
1. What is value of the variable candyChoosen if Random().nextInt(5) is 3?
val candy = listOf("Toffee", "caramels", "gummies", "chocolate", "marshmallow")
var candyChoosen = candy[Random().nextInt(5)]
2. What is the data type of the variable "cold"?
var temp = 45
var cold = temp < 20
3. How do you get a random value between 0 & 5?
4. (True or False)The following two variables will have the same value:
val firstNumber = 56.rem(5)
val secondNumber = 56%5
Thank you for reading my post. You can subscribe to my blog or follow me on Twitter to be the first person to read my new posts.
How long it took me to develop BubbleNum
Well, I started learning Android development in October 2020 but it was actually Android with Java. At that time I was taking CS50 course on EDX platform. This course had few tracks then: Web development, Android App development, IOS App development and Game development. Since I wanted to become an Android developer, I chose the Android with Java track. But it was very challenging and unfortunately I could not finish my first assignment. I even tried to take courses on Udemy which were about Android with Java and Java OOP concepts but still could not finish the assignment. The Udemy courses were great, though, I learned a lot about Android development and Java. After failing to finish the Android Track, I decided to focus on learning Kotlin, which is more concise than Java. I talked about the courses I studied here.
On December 2020, I started building my app, BubbleNum. The app was just a way for me to practice my acquired skills and to learn more by doing an actual app. It was the best decision I made and I think I could have started earlier. When I first started, I did not know what I was supposed to do. I was kinda lost, actually. For example, what layout should I choose, Would I make an activity for each game screen, shall I use a fragment.... etc. The concepts were not that clear for me then; it was as if I have not been learning anything for the past two months. So, I just googled almost every single thing. The difference between constraint layout and relative layout, when to use each of them, what views are better for this feature.... etc. There were a lot of ups and downs in this journey. But I am glad I did it. Learning by doing is the best approach when it comes to learning programming.
I finished the main logic of the app in 3 weeks actually, but after getting feedback, I knew I still have a long way ahead. For example, More features needed to be implemented, which resulted in needing me to make classes to avoid repeating myself, which took forever actually. The concept of classes was still new to me then. But After I understood it and used it in my app, just wow. It was really great. It was so easy-to-use and implement. The amount of work that would be reduced after using classes was outstanding. I kept adding feature after feature. And of course, adding more features means having more bugs in your app. After that time, all I was doing was debugging. every day, I find a new bug, and fixing one bug introduces another one. It was so frustrating. I thought I am definitely doing something wrong, why do I have so many bugs! I always felt discouraged and wanting to stop developing. But gladly I had the best dev community on Twitter who were always supporting and encouraging me to fix the bugs and keep going! Honestly, doing the 100 days of code challenge and tweeting about it was a brilliant decision. I encourage you to do it if you want to commit to learning something. Gladly, I finally finished the app on April 2021 and uploaded the final version on Google Play. It took around 24 hours to get reviewed and approved.
So to summarize, It took me four months to develop the app from start to finish and Six months since I started learning Android development.
Mistakes I made while developing my first AppDesigned By Freepik
- Not designing the App before starting coding (Both UI/UX).
- Not deciding about the features of the App from the beginning.
- Using more activities than needed. Since the activities have the same views but different content.
- Not using classes from the beginning.
- Not having the final UI elements before coding.
- Not using a style resource file from the start. You will change only one line to change a view’s design or style.
- Not being patient to learn new things.
- Wanting to fix a problem right away.
- Giving up too soon when trying to fix a bug.
- I haven’t been convinced that it is normal not to know how to do things at the start and it is ok to either search or ask someone.
- Testing Testing Testing is more important than you think. Several people testing a feature is a must not just one or two.
- You have to simulate a normal user’s behavior or monitor the users while using your application to understand their behavior more & update accordingly
- Don’t Don’t Don’t depend on your own assumptions when testing your application. The users probably have different behaviors from your own.
Thank you for reading my post. You can follow me on Twitter to be the first person to read my new posts.
Introduction
This is the second part of Kotlin Basics. The first part was about Basic types, Operators, Conditions, Variables and Nullability. You can check it here. In this article, I will talk about Strings, Boolean data Types, Boolean Operators, Lists, Arrays, Lists VS arrays and finally Loops. A quiz will be included at the end of the article, as this will give an indication of whether you have absorbed the concepts covered here or not. As I said before, You don't have memorise the syntax, as you can check for any cheat sheets.
To practice Kotlin
- Open Android studio
- Choose a new Empty Activity > Next > Name the project > Choose Kotlin Language > Finish
- Click on tools > Kotlin > Kotlin REPL
- The REPL will appear in the window's bottom
- Press Ctrl + Enter to execute any code
Strings in Kotlin
Strings in Kotlin are pretty much the same as in any other languages. Check the following code for the features:
//Concatenation
val firstName = "Leila"
val lastName = "Kim"
firstName + lastName
res0: kotlin.String = LeilaKim
"Leila" + "Kim"
res1: kotlin.String = LeilaKim
//Building a String and Replacing text by its value using the dollar sign
"My name is $firstName"
res2: kotlin.String = My name is Leila
//We can use any type even an Integer
val age = 20
"$firstName is $age years old."
res3: kotlin.String = Leila is 20 years old.
//Integers can get added first before being displayed in the result
val brother = 1
val sister = 1
"$firstName has ${brother + sister} siblings"
res4: kotlin.String = Leila has 2 siblings
Boolean data types And Boolean Operators in Kotlin
Kotlin has Boolean data types just like other languages. Its value can either be true or false.
// A variable of type Boolean with value true
val isEmpty: Boolean = true
// A variable of type Boolean with value false
val isFull: Boolean = false
Boolean Operators are logical equality operators to compare between two values, and the result would be a boolean value of either true or false.There are logical boolean operators used with conditions to make the program flow control logic. Check the examples below:
//Two variables of value 21 and 18
val leilaAge = 21
val sisterAge = 18
//Equal comparison "use a double equal sign"
//Is 21 equal to 18? No, so the output is false
leilaAge == sisterAge
res0: kotlin.Boolean = false
//Not equal comparison
//Is 21 not equal to 18? Yes, so the output is true
leilaAge != sisterAge
res2: kotlin.Boolean = true
//Greater than comparison
leilaAge > sisterAge
res3: kotlin.Boolean = true
//Greater than or equal comparison
leilaAge >= sisterAge
res4: kotlin.Boolean = true
//Less than comparison
leilaAge < sisterAge
res5: kotlin.Boolean = false
//Less than or equal comparison
leilaAge <=sisterAge
res6: kotlin.Boolean = false
Conditions in Kotlin
There are two basic ones in Kotlin, they are if-else and when. We can nest them as well, which means we can use if then else if then else. So testing for conditions is as follows:
//If - else statement
// if the condition is true, the program executes a
certain block of code, if the condition is false, the program executes the
block of code after "else"
if(sisterAge>=16) println("she can drive")
else println("She can not drive ")
Output: she can drive
//Kotlin lets use range of values inside the
condition
if(sisterAge in 13..19) println("Still a
teenager")
Output: Still a teenager
//when is like switch for other languages
when(sisterAge){
6 -> println("A child")
18 -> println("A
teenager")
21 -> println("An
adult")
}
Output: A teenager
Lists in Kotlin
There are two types, List<T> and MutableList<T>. List<T> has objects with specified order while MutableList<T> has objects where we can add or remove elements from inside the list. As follows:
//A list of elements of type integer
val numbers:List<Int> = listOf(1,2,3,4)
println("The size of the list is ${numbers.size}")
The size of the list is 4
println("The first element is ${numbers.get(0)}")
The first element is 1
//A mutable list of elemets of type integers
val mutableNumbers:MutableList<Int> = mutableListOf(1,2,3,4)
println("The size of the list is ${mutableNumbers.size}")
The size of the list is 4
println(mutableNumbers.add(0,0))
kotlin.Unit
println(mutableNumbers)
[0, 1, 2, 3, 4]
mutableNumbers.removeAt(4)
res0: kotlin.Int = 4
println(mutableNumbers)
[0, 1, 2, 3]
Arrays in Kotlin
We can create an array using arrayOf(). There are primitives type arrays as well: ByteArray, ShortArray & IntArray. As the name suggests, They are for byte, short & Int data types, respectively. Few Examples below:
//An array of Strings
val movies = arrayOf("Harry Potter", "Lord of the rings", "star wars")
//We can make an array of mixed data types
val mixedArray = arrayOf("Harry Potter", 8)
//We can nest arrays so we have an array of arrays, When we print it, we can not really see the elements inside the Array as follows:
val nestedArray = arrayOf(movies, arrayOf(1,2,3))
println(Arrays.toString(nestedArray))
[[Ljava.lang.String;@7be677a6, [Ljava.lang.Integer;@580901ca]
//An int array
val numbers: IntArray = intArrayOf(1,2,3)
//An int array of size 7 with values [0,0,0,0,0,0,0]
val zeroArray = IntArray(7)
//An int array of size 6 with values [5,5,5,5,5,5]
val arrayOfFive = IntArray(6){5}
//An int array of size 6 with its values equal to their index value
var arrayOfIndex = IntArray(6){it*1}
Printing an array or accessing its elements is a bit tricky. To print an array:
///First way to print an array
Arrays.toString(zeroArray)
res0: kotlin.String! = [0, 0, 0, 0, 0, 0, 0]
Arrays.toString(arrayOfFive)
res1: kotlin.String! = [5, 5, 5, 5, 5, 5]
Arrays.toString(arrayOfIndex)
res2: kotlin.String! = [0, 1, 2, 3, 4, 5]
//Another way to print an array "Note: Loops will be explained later in this Article"
for(element in arrayOfIndex){
println(element)
}
012345
//Third way to print an array
arrayOfIndex.forEach { println(it) }
012345
//A Fourth way to print an array
println(arrayOfIndex.asList())
[0, 1, 2, 3, 4, 5]
Arrays Vs Lists in Kotlin
Check the code below:
//Changing the value of the first element in an array
//Before
var arrayOfIndex = IntArray(6){it*1}
println(arrayOfIndex.asList())
[0, 1, 2, 3, 4, 5]
//After
arrayOfIndex[0] = 1
println(arrayOfIndex.asList())
[1, 1, 2, 3, 4, 5]
//Trying to Change the value of the first element in a list
val numbers:List<Int> = listOf(1,2,3,4)
numbers[0] = 2
error: unresolved reference.
Loops in Kotlin
Loops are like every other programming languages, we can iterate over an iterable object. As follows:
//Looping over the index and elements at the same time
//withIndex() make an object iterable that contains the index of the element and its value
for ((index, element) in movies.withIndex()){
println("Movie at $index is $element ")
}
Movie at 0 is Harry Potter Movie at 1 is Lord of the rings Movie at 2 is star wars
//Looping over ranges of different types
//Looping over range of alphabets, be careful to use a single quotations for a character instead of double quotations that is used for a string
for(e in 'a'..'d') println(e)
abcd
//Looping over range of numbers
for(e in 2..8) println(e)
2345678
//Looping over numbers going downward
for(e in 9 downTo 0 ) println(e)
9876543210
//Looping over numbers with different step
for(e in 2..8 step 2) println(e)
2468
This is how While loop works: as long as the condition is true, a block of code would be executed. While loop has continue and break with an ability to referencing and labeling the loop using @ symbol. Continue is for skipping a loop and break is for stopping the loop.
var Timer = 20
while (Timer>0){
println(Timer)
Timer--
}
2019181716151413121110987654321
Quiz
1. What is the output for this line of code:
val mutableNumbers = mutableListOf("one", "two", "three", "four")
println(mutableNumbers[1])
2. What is the output of this code:
val numbers = listOf("one", "two", "three", "four")
println(numbers.indexOf("three"))
3. Val array = //array initialization here
val movies = arrayOf("Harry Potter and the Philosopher's stone", "Harry Potter and the Chamber of Secrets", "Harry Potter and the Prisoner of Azkaban","Harry Potter and the Goblet of Fire", "Harry Potter and the Order of the Phoenix", "Harry Potter and the Half-Blood Prince", "Harry Potter and the Deathly Hallows part 1", "Harry Potter and the Deathly Hallows part 2")
for ((i, value) in array.withIndex()) {
println(" ${movies[i]} is movie number ${value.toString()} ")
println(" \n")
}
Which array initialization will generate the following output ?
Harry Potter and the Philosopher's stone is movie number 1
Harry Potter and the Chamber of Secrets is movie number 2
Harry Potter and the Prisoner of Azkaban is movie number 3
Harry Potter and the Goblet of Fire is movie number 4
Harry Potter and the Order of the Phoenix is movie number 5
Harry Potter and the Half-Blood Prince is movie number 6
Harry Potter and the Deathly Hallows part 1 is movie number 7
Harry Potter and the Deathly Hallows part 2 is movie number 8
Harry Potter and the Chamber of Secrets is movie number 2
Harry Potter and the Prisoner of Azkaban is movie number 3
Harry Potter and the Goblet of Fire is movie number 4
Harry Potter and the Order of the Phoenix is movie number 5
Harry Potter and the Half-Blood Prince is movie number 6
Harry Potter and the Deathly Hallows part 1 is movie number 7
Harry Potter and the Deathly Hallows part 2 is movie number 8
4. What is the output of this code:
var hotelLevel = 1
when(hotelLevel) {
0 -> println("Lobby")
in 1..9 -> println("Rooms floors")
10 -> println("Roof")
else -> println("Not inside the Hotel")
}
Thank you for reading my post. You can subscribe to my blog or follow me on Twitter to be the first person to read my new posts.
Introduction
In this article, I will talk about Kotlin basics: Basic types, Operators, Variables and Nullability. At the end of the article, there is a quiz to check your understanding of the concepts explained. We don't really have to memorise the syntax of any programming language. Most senior developers google printing a string in a specific language, We need to focus more on practicing the concepts as there are tons of cheat sheets out there, In addition, I will provide at the end of the articles' series.
To practice Kotlin
- Open Android studio
- Choose a new Empty Activity > Next > Name the project > Choose Kotlin Language > Finish
- Click on tools > Kotlin > Kotlin REPL
- The REPL will appear in the window's bottom
- Press Ctrl + Enter to execute any code
Basic Types in Kotlin
Kotlin treats everything as if they are objects, so primitive types such as numbers, booleans and characters are objects. This means that we can call methods on them. For example, we can call the following methods on numbers: toLong(), toByte(), toInt() and more.
Numbers have a supertype called Number. Supertype is "a generic entity type that has a relationship with one or more subtypes" as Oracle explains it.
Kotlin allows us to use object wrappers, which is a class that encases a primitive data type or another object to either convert it to a class or make it compatible with a newer version. It is called boxing. This will be explained later when needed.
Operators in Kotlin
These are the mathematical operators:
//Addition
2 + 2
res0: kotlin.Int = 4
//Subtraction
99 - 12
res1: kotlin.Int = 87
//Division
20 / 5
res2: kotlin.Int = 4
3 / 6
//Integer divided by Integer returns Integer
res3: kotlin.Int = 0
3.0 / 6.0
// Float divided by float returns float
res4: kotlin.Double = 0.5
//Multiplication
6 * 30
res5: kotlin.Int = 180
//Multiplication
3.times(6)
res0: kotlin.Int = 18
//Division
18.div(2)
res1: kotlin.Int = 9
//Addition
9.plus(2)
res2: kotlin.Int = 11
//Subtraction
15.minus(2)
res3: kotlin.Int = 13 reres: kotlin.Int = 9s1: kotlin.Int = 9
Variables in Kotlin
There are two ways to define variables in Kotlin:
//A variable of type string called firstName of value Leila
val firstName: String = "Leila"
//A variable of type integer called age of value 20
var age: Int = 20
//The type, Int, is inferred in the next line of code
//Once the type of the variable is determined, you cannot change it later.
var age = 20
//The type is needed in the next line of code, since it is not initialized
var age: Int
Basic Types in Kotlin Cont.
Numbers will not convert their type once we assign them. As the next example shows, we will get an error for mismatched type.
val byteNumber: Byte = 2
val intNumber: Int = byteNumber
error: type mismatch: inferred type is Byte but Int was expected
To solve this problem, you can cast the variable as follows:
val byteNumber: Byte = 2
val intNumber: Int = byteNumber.toInt()
Koltin recognizes variable types when we use underscores for long constants, which means the type is inferred. As follows:
val threeMillion = 3_000_000
Nullability in Kotlin
In Kotlin, Null pointer exception is avoided. Null pointer exception is when an application attempts to use a null value where an object is needed. You can check "Hello, Kotlin!" blog post to check my illustration to explain Null. By default, we can't assign a Null value to a variable, but we can use the question mark operator that will specify that this variable can be Null. Check the code below:
val pizza: Int = null
error: null can not be a value of a non-null type Int
//The correct way
val pizza: Int? = null
//Another correct way, here its type is inferred
val pizza = null
For complex data types, for example, a list, the list itself can be null and / or its elements. If the value of the list is not null, the elements themselves cannot be null. This means, If the list is nullable, its value has two options: null or a list of elements. These lists of elements if they are a nullable type, they can be null otherwise they cannot. Lists will be explained later. But lets check its syntax:
//A list of two elements that are Null
var pizzaTypes: List<String?> = listOf(null, null)
//Another correct way
listOf(null, null)
res0: kotlin.collections.List<kotlin.Nothing?> = [null, null]
//A null list
var pizzaTypes: List<String>? = null
//A null list & null elements
var pizzaTypes: List<String?>? = null
pizzaTypes = listOf(null, null)
// If the value of the list is not null, and the elements are not of a nullable type, then the elements themselves cannot be null.
var pizzaTypes: List<String>? = listOf(null, null)
error: type inference failed. Expected type mismatch: inferred type is List<String?> but List<String>? was expected
There is a way to not avoid the null exception, we can throw an exception when the value is null. By using the double exclmation mark, also called "double bang", we can do so as follows:
var cookies: Int? = 4
cookies= null
cookies!!.plus(3)
kotlin.KotlinNullPointerException
Null Testing with Question Mark Operator
By using this method, it will reduce the use of if-else statements. ?: is called the elvis operator.
//The following line of code means, If drinks is not null, the output would be a value which in this case 7, as dec will decrement the value of drinks so 8-1= 7, but if it was null, the output would have been 0
var drinks = 8
drinks?.dec() ?: 0
res0: kotlin.Int = 7
Now it is time for a quiz.
Quiz
1. What is the output for this line of code: 9 / 2 ?
2. Which Variable keyword you can use that can be reassigned?
3. Which one is the correct syntax?
4. What is the output of this code:
var chips: Int? = null
chips?.dec() ?: 0
Thank you for reading my post. You can subscribe to my blog or follow me on Twitter to be the first person to read my new posts.
ABOUT ME
Hi! I am Rayda. An Electrical Engineer, MBA holder on a journey to becoming a great programmer. I have a passion for learning new things. Programming is my new adventure. Currently, I am learning game development using Unity and C#. I have already published two games on Google play store. Since Design have always been my passion, I started learning illustrations and UI/ UX Design.
POPULAR POSTS
Contact form
Powered by Blogger.