Introduction
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
//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
// 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
//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
//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}
///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
//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
//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
var Timer = 20
while (Timer>0){
println(Timer)
Timer--
}
2019181716151413121110987654321
Quiz![A book with right and wrong illustartion A book with right and wrong illustartion](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjS6n0xPAMXBAJyt77e94XqqCMbvJs9fXwJMho_zTE6FEy5A97HNCviNy0o_rHxkCGsKaHsHMRli9vkOk-ZORD27QDJCn7te7HfD7mIReWDweDKuoUNIfRtVp0xCX_61ROJ3_PB_tUrPSE/s16000/Web+1920+%25E2%2580%2593+4%25402x.png)
1. What is the output for this line of code:
println(mutableNumbers[1])
2. What is the output of this code:
println(numbers.indexOf("three"))
3. Val array = //array initialization here
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 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:
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.
0 Comments