Kotlin Functions Part 1

   

Kotlin logo

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

  1. Open Android studio
  2. Choose a new Empty Activity > Next > Name the project > Choose Kotlin Language > Finish
  3. Click on tools  > Kotlin > Kotlin REPL
  4. The REPL will appear in the window's bottom
  5. 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


QuizA book with right and wrong illustartion

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.

0 Comments