0% found this document useful (0 votes)
72 views23 pages

KOTLIN DOCS

Uploaded by

Aneesh Shinde
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views23 pages

KOTLIN DOCS

Uploaded by

Aneesh Shinde
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Kotlin Standard Input/Output

Kotlin standard I/O operations are performed to


flow sequence of bytes or byte streams from input
device such as Keyboard to the main memory of
the system and from main memory to output
device such as Monitor.
In Java, we use System.out.println(message) to
print output on the screen but, in Kotlin
println(message) is used to print.
Kotlin Output –

Kotlin standard output is the basic operation


performed to flow byte streams from main
memory to the output device. You can output any
of the data types integer, float and any patterns or
strings on the screen of the system.
You can use any one of the following function to
display output on the screen.
print() function
println() function
Here is the Kotlin program for standard output.
 Kotlin
fun main(args: Array<String>)

print("Hello, Geeks! ")

println("This is Kotlin tutorial.")

Output:
Hello, Geeks! This is Kotlin tutorial.

Difference between println() and print() –

print() function prints the message inside the


double quotes.

println() function prints the message inside the


double quotes and moves to the beginning of the
next line.

kotlin program to print string:

 Kotlin
fun main(args

: Array<String>)

println("GeeksforGeeks")

println("A Computer Science portal for Geeks")

print("GeeksforGeeks - ")

print("A Computer Science portal for Geeks")

Output:
GeeksforGeeks
A Computer Science portal for Geeks
GeeksforGeeks - A Computer Science portal for
Geeks
Print literals and Variables –

 Kotlin

fun sum(a: Int,b: Int) : Int{

return a + b

fun main(args: Array<String>){

var a = 10

var b = 20

var c = 30L

var marks = 40.4

println("Sum of {$a} and {$b} is : ${sum(a,b)}")

println("Long value is: $c")


println("marks")

println("$marks")

Output:
Sum of {10} and {20} is : 30
Long value is: 30
marks
40.4

Kotlin Expression, Statement and Block

Kotlin Expression –

An expression consists of variables, operators,


methods calls etc that produce a single value. Like
other language, Kotlin expression is building
blocks of any program that are usually created to
produce new value. Sometimes, it can be used to
assign a value to a variable in a program. It is to
be noted that an expression can contain another
expression.
 A variable declaration can not be an expression
(var a = 100)
 Assigning a value is not an expression (b = 15)

 A class declaration is not an expression (class

XYZ {….})
Note: In Kotlin every function returns a value
atleast Unit, so every function is an expression.

fun sumOf(a:Int,b:Int): Int{

return a+b

fun main(args: Array<String>){

val a = 10

val b = 5

var sum = sumOf(a,b)

var mul = a * b

println(sum)
println(mul)

Output:
15
50

Here, a * b and sumof(a, b) both are expressions


and return integer value. sumOf() is a function
and returns the sum of two parameters passed to
it.

Kotlin else if
Use else if to specify a new condition if the first
condition is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is
true
} else if (condition2) {
// block of code to be executed if the condition1 is
false and condition2 is true
} else {
// block of code to be executed if the condition1 is
false and condition2 is false
}
Example
val time = 22
if (time < 10) {
println("Good morning.")
} else if (time < 20) {
println("Good day.")
} else {
println("Good evening.")
}
// Outputs "Good evening."
Kotlin If..Else Expressions
In Kotlin, you can also use if..else statements as
expressions (assign a value to a variable and return
it):
Example
val time = 20
val greeting = if (time < 18) {
"Good day."
} else {
"Good evening."
}
println(greeting)

When using if as an expression, you must also


include else (required).
Note: You can ommit the curly
braces {} when if has only one statement:
Example
fun main() {
val time = 20
val greeting = if (time < 18) "Good day." else
"Good evening."
println(greeting)
}

Kotlin when
Instead of writing many if..else expressions, you
can use the when expression, which is much easier
to read.
It is used to select one of many code blocks to be
executed:
Example
Use the weekday number to calculate the weekday
name:
val day = 4

val result = when (day) {


1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid day."
}
println(result)

// Outputs "Thursday" (day 4)

The when expression is similar to


the switch statement in Java.
This is how it works:
 The when variable (day) is evaluated once
 The value of the day variable is compared
with the values of each "branch"
 Each branch starts with a value, followed by
an arrow (->) and a result
 If there is a match, the associated block of
code is executed
 else is used to specify some code to run if
there is no match
 In the example above, the value of day is 4,
meaning "Thursday" will be printed

Kotlin While Loop


Loops
Loops can execute a block of code as long as a
specified condition is reached.
Loops are handy because they save time, reduce
errors, and they make code more readable.

Kotlin While Loop


The while loop loops through a block of code as
long as a specified condition is true:
Syntax
while (condition) {
// code block to be executed
}
In the example below, the code in the loop will
run, over and over again, as long as the counter
variable (i) is less than 5:
Example
var i = 0
while (i < 5) {
println(i)
i++
}

The Do..While Loop


The do..while loop is a variant of the while loop.
This loop will execute the code block once, before
checking if the condition is true, then it will repeat
the loop as long as the condition is true.
Syntax
do {
// code block to be executed
}
while (condition);
The example below uses a do/while loop. The loop
will always be executed at least once, even if the
condition is false, because the code block is
executed before the condition is tested:
Example
var i = 0
do {
println(i)
i++
}
while (i < 5)

Kotlin Break and Continue

Kotlin Break
The break statement is used to jump out of a loop.
This example jumps out of the loop when i is equal
to 4:
Example
var i = 0
while (i < 10) {
println(i)
i++
if (i == 4) {
break
}
}
Try it Yourself »

Kotlin Continue
The continue statement breaks one iteration (in the
loop), if a specified condition occurs, and
continues with the next iteration in the loop.
This example skips the value of 4:
Example
var i = 0
while (i < 10) {
if (i == 4) {
i++
continue
}
println(i)
i++
}
Kotlin For Loop

Kotlin For Loop


Often when you work with arrays, you need to
loop through all of the elements.
To loop through array elements, use the for loop
together with the in operator:
Example
Output all elements in the cars array:
val cars = arrayOf("Volvo", "BMW", "Ford",
"Mazda")
for (x in cars) {
println(x)
}
Try it Yourself »
Example
val nums = arrayOf(1, 5, 10, 15, 20)
for (x in nums) {
println(x)
}

Kotlin Functions

A function is a block of code which only runs


when it is called.
You can pass data, known as parameters, into a
function.
Functions are used to perform certain actions, and
they are also known as methods.
In Kotlin, functions are used to encapsulate a
piece of behavior that can be executed multiple
times. Functions can accept input parameters,
return values, and provide a way to encapsulate
complex logic into reusable blocks of code.
Example of a Function
For example: If we have to compute the sum of
two numbers then define a fun sum().
fun sum(a: Int, b: Int): Int {
Int c = a + b
return c
}

Parameters in Function

Function parameters are the defined as the


elements that are passed to the function for further
processing where operations are performed.
In above example, there are two parameters
passed mentioned:
 a of Integer type

 b of Integer type

Body of Function
Here in the body we perform the operations to be
performed in the function like in the above
Example:

val c = a + b
Return Value
Return value is the value which is returned after
the operation is performed in the function. In
above example c is the value which is returned.
Types of Functions in Kotlin
In Kotlin, there are two types of functions:
 User-defined function

 Standard library function

1. Kotlin User-Defined Function


A function that is defined by the user is called a
user-defined function. As we know, to divide a
large program into small modules we need to
define function. Each defined function has its own
properties like the name of the function, return
type of a function, number of parameters passed
to the function, etc.

-> Creating User-Defined Function


In Kotlin, the function can be declared at the top,
and no need to create a class to hold a function,
which we are used to doing in other languages
such as Java or Scala. Generally, we define a
function as:
fun fun_name(a: data_type, b: data_type, ......):
return_type {
// other codes
return
}
 fun– Keyword to define a function.
 fun_name – Name of the function which later

used to call the function.


 a: data_type – Here, a is an argument passed

and data_type specify the data type of argument


like integer or string.
 return_type – Specify the type of data value

return by the function.


 {….} – Curly braces represent the block of

function.
Kotlin function mul() to Multiply two Numbers
having same type of Parameters:

fun mul(num1: Int, num2: Int): Int {


var number = num1.times(num2)
return number
}

-> Calling of User-Defined Function


We create a function to assign a specific task.
Whenever a function is called the program leaves
the current section of code and begins to execute
the function.
The flow-control of a function:
1.The program comes to the line containing a
function call.
2.When function is called, control transfers to that
function.
3.Executes all the instruction of function one by
one.
4.Control is transferred back only when the
function reaches closing braces or there any
return statement.
5.Any data returned by the function is used in
place of the function in the original line of code.
Kotlin program to call the mul() function by
passing two arguments:
Kotlin
fun mul(a: Int, b: Int): Int {
var number = a.times(b)
return number
}
fun main(args: Array<String>) {

var result = mul(3,5)


println("The multiplication of two numbers is:
$result")
}
Output:
The multiplication of two numbers is: 15
Explanation: In the above program, we are
calling the mul(3, 5) function by passing two
arguments. When the function is called the control
transfers to the mul() and starts execution of the
statements in the block. Using in-built times() it
calculates the multiple of two numbers and store
in a variable number. Then it exits the function
with returning the integer value and controls
transfer back to the main() where it calls mul().
Then we store the value returned by the function
into mutable variable result and println() prints it
to the standard output.

Advantages and Disadvantages in Kotlin Function


-> Advantages of Using functions in Kotlin
1.Modularity: Functions provide a way to
modularize your code and break it down into
smaller, more manageable parts. This makes
your code more readable, maintainable, and
easier to test.
2.Reusability: Functions can be called from
multiple locations in your code, making it easy
to reuse your code and avoid duplication.
3.Improved Readability: Functions provide a way
to encapsulate complex logic into reusable
blocks of code, which can make your code more
readable and easier to understand.
4.Improved Abstraction: Functions can be used
to abstract away complex logic, making it easier
to understand what a piece of code does without
having to examine its implementation details.
-> Disadvantages of Using functions in Kotlin
1.Overhead: Functions can increase the size of
your code and increase the amount of memory
required to execute it, especially if you have
many functions.
2.Debugging: Functions can make debugging
more difficult if you have complex logic inside
your functions, especially if you have multiple
functions that call each other.

You might also like