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

Unit 1 Introduction To Android and Kotlin

andlpef

Uploaded by

jashanpreet58334
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
72 views79 pages

Unit 1 Introduction To Android and Kotlin

andlpef

Uploaded by

jashanpreet58334
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 79

Introduction to Android

and Kotlin
What is Kotlin ?
Kotlin = Java + Extra updated
new features.
• Kotlin is a general-purpose, statically typed, and open-
source programming language.
• It runs on JVM and can be used anywhere Java is used
today.
• It can be used to develop Android apps, server-side
apps and much more.
• It has built world-class IDEs like IntelliJ IDEA, PhpStorm,
Appcode, etc.
History of Kotlin

• It was first introduced by JetBrains in 2011 as


a new language for the JVM.
• Kotlin is an object-oriented language.
• Kotlin mainly targets the Java Virtual Machine
(JVM), but also compiles to JavaScript.
• Kotlin is influenced by other popular
programming languages such as Java, C#,
JavaScript, Scala and Groovy.
• Kotlin is sponsored by Google, announced as
one of the official languages for Android
Development in 2017.
Features of Kotlin
• Statically typed – Statically typed is a programming language
characteristic that means the type of every variable and
expression is known at compile time.
• Concise: Kotlin reduces writing the extra codes, it has less
boilerplate code.
• Null safety: Kotlin is null safety language. Kotlin aimed to
eliminate the NullPointerException (null reference)
• Interoperable: Kotlin and java code are inter-accessible
• Type Inference: Kotlin's compiler can automatically infer the
type of a variable based on the assigned value, reducing the
need for explicit type declarations
• Smart cast: Kotlin automatically casts variables to their correct
types when it is safe to do so, simplifying type checks and
casting operations. Kotlin has safe casting operator (as?) which
returns ‘null’ if cast is not possible , this prevents run time
exceptions
• Tool-friendly: Kotlin programs are build using the command line
as well as any of Java IDE
• Multiplatform Support: Kotlin supports multiple platforms,
including JVM, Android, JavaScript, and native platforms, allowing
Kotlin Drawbacks
• Compilation Speed: Kotlin's compilation time can be slower
compared to Java in large projects.
• Limited Resources: Despite its growing popularity, Kotlin has
fewer resources, tutorials, and community support compared to
more established languages like Java.
• Tooling and IDE Support: Although Kotlin is supported by
major IDEs like IntelliJ IDEA and Android Studio, the support is not
as mature or extensive as it is for Java, potentially leading to less
efficient development workflows.
• Runtime Size: Kotlin applications may have a larger runtime size
compared to Java applications, which can be a concern for Android
developers trying to minimize the apk file size
• Frequent Updates: The Kotlin language and its ecosystem are
evolving rapidly, which can lead to frequent updates and the
need to keep up with changes, potentially causing compatibility
issues with existing code.
Applications of Kotlin language
• Android Development : It is widely used for building Android applications due to its
concise syntax, null safety features, and interoperability with Java. Major apps like
Pinterest, Trello, Evernote, and Netflix have adopted Kotlin for their Android
development.
• Server-Side Development : Kotlin can be used to build server-side applications using
frameworks like Ktor, Spring, and Vert.x. Kotlin is suitable for developing microservices,
benefiting from its concise code and interoperability with Java-based microservices
frameworks.
• Web Development : Kotlin enables full-stack development by allowing developers to
use the same language for both backend and frontend development.
• Multiplatform Development : this feature allows developers to share code across
different platforms, including Android, iOS, web, and desktop applications. It facilitates
code reuse and reduces duplication.
• Data Science and Machine Learning : Kotlin can be used for data processing and
analysis with libraries like KotlinDL (Deep Learning), Kotlin Statistics. Kotlin can
leverage existing Java libraries and frameworks for data science, such as Apache
Spark, Deeplearning4j, and Weka.
• Desktop Applications : Kotlin can be used to develop desktop applications using JavaFX,
providing a modern alternative to Swing.
• IoT Applications: Kotlin can be used to develop applications for IoT devices,
leveraging its concise syntax and interoperability with Java-based IoT frameworks.
• Coroutines: Kotlin's coroutines provide an efficient way to handle concurrency and
parallelism, making it suitable for applications that require high performance and
responsiveness, such as real-time data processing and network applications.
Kotlin Jobs Opportunity
• Kotlin is very high in demand and all major companies are moving
towards Kotlin to develop their web and mobile applications. Average
annual salary for a Kotlin developer is around ₹ 3.6 Lakhs to ₹ 35.0
Lakhs . Following are the great companies who are using Kotlin:
• Google
• Amazon
• Netflix
• Pinterest
• Uber
• Trello
• Coursera
• Basecamp
• Corda
• JetBrains
• Many more...
Installing Kotlin
• Like Java, Kotlin also runs on JVM therefore to install Kotlin
on Windows directly and work with it using the command
line You need to make sure you have JDK installed in your
system.

Verifying the Java installation


• To verify Java installation −
C:\> java -version
If Java is not intalled on your system than You can install
JDK Java SE 8 or higher version
Install IDE for Kotlin
• There are various Java IDE available which supports
Kotlin project development. We can choose these IDE
according to our compatibility. The download links of
these IDE's are given below.
IDE Name Download links
IntelliJ IDEA https://www.jetbrains.com/idea/d
Android ownload/
https://developer.android.com/st
Studio udio/preview/index.html
Eclipse https://www.eclipse.org/download
s/
Kotlin - Basic Syntax

• Program Entry Point - An entry point of a


Kotlin application is the main() function. A
function can be defined as a block of code
designed to perform a particular task.
fun main()
• Entry Point with Parameters- Another form
of main() function accepts a variable
number of String arguments as follows:
fun main(args: Array<String>)
print() vs println()
• The print() is a function in Kotlin which prints its
argument to the standard output, similar way
the println() is another function which prints its
argument on the standard output but it also adds a line
break in the output.
Kotlin - Comments
• Kotlin supports single-line (or end-of-line) and multi-
line (block) comments.
1. // This is single-line comment
2. /* This is a
multi-line
comment */
KEYWORDS IN KOTLIN

• Kotlin keywords are predefined, reserved words used in


Kotlin programming that have special meanings to the
compiler.
• These words cannot be used as an identifier (variables
names, package names, function names etc.)
• Program will not compile when keywords are used as
identifiers.
fun main(args: • The code shown alongside
Array<String>) { will give error because
var a=40 “try” is a reserved
keyword.
print(a)
• Replace the “try” keyword
var try = 40 with some other variable
print(try) name to make code work
} • Reserved keywords can be
used as special identifiers
by using backtick (`) if
fun main(args: Array<String>) { required
var a=40
print(a)
var `try` = 40
print(`try`)
}
Variables
• They are the names you give to computer memory
locations which are used to store values in a computer
program and later you use those names to retrieve the
stored values and use them in your program.

• Kotlin variables are created using


either var or val keywords and then an equal sign = is
used to assign a value to those created variables.
Mentioning the type of variable is optional in Kotlin
var name = ”Shyam”
var age = 19
var height = 5.2
DECLARING VARIABLES

• Mutable Variables: declared using keyword `var`.


These can be changed after initialization
var age: Int = 25
age = 26 // Valid because age is a mutable
variable
• Immutable Variables: declared using keyword `val`.
These cannot be changed once initialized.
val age: Int = 25
age = 26 //will give error since age is
immutable variable
Kotlin Variable Naming
Rules
• Kotlin variable names can contain letters, digits,
underscores, and dollar signs.
• Kotlin variable names should start with a letter
or underscore
• Kotlin variables are case sensitive which means
LPU and lpu are two different variables.
• Kotlin variable can not have any white space or
other control characters.
• Kotlin variable can not have names like var, val,
String, Int because they are reserved keywords
in Kotlin.
Variable Initialization

• Value can be assigned to a variable either at Initialization or


anywhere else in the program
• Value of an immutable variable can be assigned only once and for a
mutable variable value can be changed as and when required
• If a variable is not initialized while defining it, then it is compulsory to
mention the type of variable
• fun main()
{
var a = 10 //initialized while defining variable
var b:Int //defined but not initialized
var c: Int
b = 20
c=a+b
print(c)
}
Type Inference

• Kotlin can infer the type from the assigned value


fun main()
{
var a = 10 // Type is inferred as Integer
var b = 12.123 // Type is inferred as Float
var c = "hello" // Type is inferred as String
var d = true // Type is inferred as Boolean
}
Accessing Variables

• To read the value from a variable simply use the


variable name
fun main()
{
var age: Int = 25
println(age)
}
Variables inside functions and Class
Variables declared inside a Variables declared inside a
function are only accessible class can be accessed by all
within that function methods in the class
class Person
fun greet() {
{ var name: String = "John Doe"
val message: String = "Hello, val age: Int = 30
Kotlin!" fun displayInfo()
println(message) {
} println("Name: $name, Age:
println(message) //this will give $age")
error since variable msg is declared }}
inside the function greet therefore
only accessible inside the function fun main()
{
val person = Person()
person.displayInfo()
}
String Interpolation with $
• String interpolation fun main()
allows you to insert
variable values {
directly into a string val a = 10
using the $ symbol.
val b = 20
• String interpolation
can also be directly val result = "Sum of $a and $b is
used to evaluate {a+b}"
expressions println(result)
}
Data Types

• Kotlin treats everything as an object which


means that we can call member functions
and properties on any variable.
• Kotlin is a statically typed language, which
means that the data type of every expression
should be known at compile time.
a) Number
b) Character
c) String
d) Boolean
e) Array
Kotlin Number Data Types
Numeric values and they are divided into two groups:
(a) Integer types store whole numbers, +ve or –ve
val a: Int = 10000
(b) Floating point numbers with a fractional part, containing one or
more decimals.
val f: Float = 100.00
Data Size (bits) Data Range
Type
Byte 8 bit -128 to 127
Short 16 bit -32768 to 32767
Int 32 bit -2,147,483,648 to 2,147,483,647
Long 64 bit -9,223,372,036,854,775,808 to
+9,223,372,036,854,775,807
Float 32 bit 1.40129846432481707e-45 to
3.40282346638528860e+38
Double 64 bit 4.94065645841246544e-324 to
1.79769313486231570e+308
Kotlin Character Data Type
• Kotlin character data type is fun main()
used to store a single {
character and they are
represented by the Char val letter: Char //
keyword. defining a Char variable
• Char value must be letter = 'A' //
surrounded by single Assigning a value to it
quotes, like 'A' or '1’. print("$letter")
• Syntax : val name: Char = 'A’
print('\n') //prints a
• Kotlin supports a number of
newline character
escape sequences of
characters. When a print('\$') //prints a dollar $
character is preceded by a character
backslash (\), it is called an print('\\') //prints a back
escape sequence and it has slash \ character
a special meaning to the }
compiler.
Kotlin String Data Type
• The String data type is used to store a sequence of characters.
• String values must be surrounded by double quotes (" ") or
triple quote (""" """).
• We have two kinds of string available in Kotlin
1. Escaped String is declared within double quote (" ") and
may contain escape characters like '\n', '\t', '\b' etc.
2. Raw string is declared within triple quote (""" """) and may
contain multiple lines of text without any escape characters.
• val x : String = "I am escaped String!\n"

• var y :String = """This is going to be a


multi-line string and will
not have any escape sequence""";
Kotlin Boolean Data Type

Boolean is very simple like other programming


languages. We have only two values for Boolean data
type - either true or false

val A: Boolean = true


// defining a variable with true value
Array Data Type

• An array is a collection of elements of the


same type, stored in contiguous memory
locations.
• Arrays are useful for storing multiple
items of the same data type.
• In Kotlin, arrays are represented by the
‘Array’ class.
fun main() // Using forEach function
{ println("Words array using forEach:")
// Array of integers words.forEach { word -> println(word) }
val numbers = arrayOf(1, 2, 3, 4, 5) // Using indices property
// Array of strings println("Squares array using indices:")

val words: Array<String> = arrayOf("Kotlin", for (i in squares.indices)


"Java", "Python") {
// Array of squares using lambda function println("Element at index $i is ${squares[i]}") }
val squares = Array(5) { i -> i * i } // properties of array

// Accessing elements val size = numbers.size // Array size


println("Size of numbers array: $size")
val firstNumber = numbers[0] // First
element // isEmpty and isNotEmpty functions
val secondWord = words[1] // Second if (numbers.isEmpty())
element {
println("First number: $firstNumber") println("Numbers array is empty") }
println("Second word: $secondWord") else
// Modifying elements { println("Numbers array is not empty")
numbers[0] = 10 // Modify first element val firstElement = numbers.first() // First element

words[1] = "Kotlin" // Modify second val lastElement = numbers.last() // Last element


element println("First element: $firstElement")
println("Modified first number: $ println("Last element: $lastElement")
{numbers[0]}") val index = words.indexOf("Kotlin") // Index of
println("Modified second word: ${words[1]}") an element

// iterating over arrays println("Index of 'Kotlin': $index")


}
// Using for loop
}
println("Numbers array using for loop:")
for (num in numbers)
Multidimensional Arrays Additional Array Examples

fun main() fun main()


{
{
// Creating primitive type arrays
// Creating a 2D array val floatArray = floatArrayOf(1.1f, 2.2f,
(matrix) 3.3f)
val matrix: val intArray = intArrayOf(10, 20, 30)
Array<Array<Int>> = val doubleArray = doubleArrayOf(1.1, 2.2,
3.3)
arrayOf( arrayOf(1, 2, 3),
println("Float array: $
arrayOf(4, 5, 6), arrayOf(7, {floatArray.joinToString(", ")}")
8, 9) ) println("Int array: ${intArray.joinToString(",
println("Element at row 0, ")}")
column 1: ${matrix[0][1]}") println("Double array: $
{doubleArray.joinToString(", ")}")
} // Type conversion example
val convertedInt = doubleArray[0].toInt()
// Converting double to int
println("Converted double to int:
$convertedInt")
}
Kotlin Data Type Conversion
• Type conversion is a process in which the value of
one data type is converted into another type.
Kotlin does not support direct conversion of one
numeric data type to another. It has predefined
TYPE CHECKING option.
• To convert a numeric data type to another type,
Kotlin provides a set of functions:
• toByte()
• toShort()
• toInt()
• toLong()
• toFloat()
• toDouble()
• toChar()
Find the Error……

fun main(args: Array<String>)


{
val x: Int = 100
val y: Long = x
println(y)
}
// Here x is integer type of variable, thus it cannot
be stored y due to type mismatch
//corrected code

fun main(args: Array<String>)


{
val x: Int = 100
val y: Long = x.toLong()
println(y)
}
Safe and Unsafe Casting

• Safe Cast : done using • Unsafe Cast : done


‘as?’ keyword. It returns using ‘as’ keyword. It
null if cast is not possible throws a
ClassCastException if cast
is not possible
fun main() {
val a = "hi"
val b: String = a as String
println("Unsafe Cast Result: $b")
//val c: Int = a as Int
// println("This line will not be executed
$c")
val d: String? = a as? String //
Successful safe cast
print(d)
val e: Int? = a as? Int // Safe cast will
return null
print(e)
}
Operator
• An operator is a symbol that tells the compiler to
perform specific mathematical or logical manipulations
on operands (values or variable). Kotlin is rich in built-
in operators and provide the following types of
operators:

• Arithmetic operator
• Relation operator
• Assignment operator (Compound Assignments)
• Unary operator
• Logical operator
• Bitwise operator
Arithmetic Operators
Operator Description Expression Translate to
+ Addition a+b a.plus(b)
- Subtraction a-b a.minus(b)
* Multiply a*b a.times(b)
/ Division a/b a.div(b)
% Modulus a%b a.rem(b)
Relational Operators
Operato Expressi
Meaning Translate to
rs on
> greater than a>b a.compareTo(b) > 0

< less than a<b a.compareTo(b) < 0

greater than
>= a >= b a.compareTo(b) >= 0
or equal to

less than or
<= a <= b a.compareTo(b) <= 0
equal to

a?.equals(b) ?: (b ===
== is equal to a == b
null)

!(a?.equals(b) ?: (b ===
!= not equal to a != b
Note: ? means it could benull))
NULL>0
Assignment Operators

Operato Expressi
Translate to
rs on
+= a = a + b a.plusAssign(b) > 0
a.minusAssign(b) <
-= a=a–b
0
a.timesAssign(b)>=
*= a=a*b
0
/= a=a/b a.divAssign(b) <= 0
%= a = a % b a.remAssign(b)
Unary Operators

Operat Description Expression Convert to


or
+ unary plus +a a.unaryPlus()
- unary minus -a a.unaryMinus()
++ increment by ++a a.inc()
1
-- decrement by --a a.dec()
1
! not !a a.not()
Logical Operators
Operat Name Description Exampl
or e
&& Logical Returns true if both x && y
and operands are true

|| Logical Returns true if either of x || y


or the operands is true

! Logical Reverse the result, !x


not returns false if the
operand is true
fun main() { // Assignment Operators
var a = 10 var c = a
var b = 5 c += b
val isTrue = true val inc = c
val isFalse = false println("c += $b: $inc")
val add = a + b
//arithmetic operators // Bitwise Operators
println("Addition: $a + $b = $add") val e = 5 // 0101 in binary
println("Multiplication: $a * $b = $ val f = 3 // 0011 in binary
{a*b}")
val andBitwise = e and f
println("$e and $f: $andBitwise")
//comparison operators
val isEqual = a == b
// Range and Iterator Operators
println("$a == $b: $isEqual")
val range = 1..5
println("$a > $b: ${a>b}")
println("Range: $range")
// Logical Operators
println("Numbers in range:")
val andResult = isTrue && isFalse for (i in range) {
val notResult = !isTrue print("$i ")
println("$isTrue && $isFalse: }
$andResult") println()
println("!$isTrue: $notResult") }
Control
Flow
Kotlin flow control statements
determine the next statement to be
executed. For example, the
statements if-else, if, when, while,
for, and do are flow control
statements.
IF-ELSE

• The If-Else statements in Kotlin are fundamental control


flow constructs that allow a program to make decisions
based on certain conditions.
• They help control the flow of execution depending on
whether a condition is true or false.
• Syntax:
Simple if Statement if-else Statement

fun main() fun main()


{ {
val temperature = 25 val age = 18
if (temperature > 20) if (age >= 18) {
{ println("You are an adult.")
println("It's a warm day.") }
} else {
} println("You are a minor.")
}
}
if-else if-else Ladder Nested if Statements
fun main() fun main()
{ {
val score = 85 val age = 20
val hasID = true
if (score >= 90) {
if (age >= 18) {
println("Grade: A")
if (hasID) {
}
println("You can enter the club.")
else if (score >= 80) {
}
println("Grade: B") else {
} println("ID required to enter the
else if (score >= 70) { club.")
println("Grade: C") }
}
}
else {
else {
println("You are too young to enter the
println("Grade: D") club.")
} }
} }
Real Life Application
Design a Kotlin program for a store to determine eligibility
for a special offer based on the total amount and
membership status.
Instructions:
1.Create a Kotlin program that simulates a discount system for a
store.
2.Define two variables:
1. A variable representing the total amount of purchase.
2. A variable indicating whether the customer has a membership.
3.Implement the following logic:
1. If the total amount of the purchase is either 1000 or more
then:
a) Check if the customer has a membership.
• If they do, print a message indicating a 20% discount.
• If they do not, print a message indicating a 10% discount.
2. If the total amount of the purchase is below the threshold, print
a message indicating no discount.
fun main()
{
val purchaseAmount = 1500
val hasMembership = true
if (purchaseAmount >= 1000) {
if (hasMembership) {
println("Congratulations! You are eligible for a 20%
discount.")
}
else {
println("You are eligible for a 10% discount.")
}
}
else {
println("No discount available.")
}
}
When
• Consider a situation when you have large number of
conditions to check.
• It can be done with if..else if expression but Kotlin
provides when expression to handle the situation in a
better and clean way
• Kotlin when expression is similar to the switch
statement in C, C++ and Java.
‘when’ as an Expression

• When used as an fun main()


{
expression, ‘when’ val dayOfWeek = 3
returns a value that val dayName = when (dayOfWeek) {
can be assigned to a 1 -> "Monday "
variable or used 2 -> "Tuesday"
directly in expressions. 3 -> "Wednesday"
4 -> "Thursday"
• Syntax:
5 -> "Friday "
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid day"
}
println("Day of the week: $dayName")
}
‘when’ as a statement
• When used as a fun main()
statement, when
executes different code {
blocks based on the val number = 8
condition but does not
return a value. when {
• Syntax: number % 2 == 0 ->
println("$number is even")
number % 2 != 0 ->
println("$number is odd")
//else -> println("Unexpected
number")
}
}
‘For’ Loop

• The for loop in Kotlin is used to iterate over


a range of values, collections, or arrays.
• It's an essential control flow construct for
repeating operations and working with
sequences of data
• Kotlin for loop iterates through anything
that provides an iterator ie. that contains a
countable number of values
• The for loop in Kotlin can be used in
different ways depending on what you're
iterating over.
Syntax of ‘for’ Loop
Syntax for Ranges:

Syntax for Collections (e.g., Lists, Arrays):

Syntax for Iterating with Index:


For loop for Ranges

Both ends of range inclusive Upper end excluded


fun main() fun main() {
{ for (i in 1 until 5) {
for (i in 1..5) { println("Number: $i")
println("Number: $i") }
} }
}
Reverse loop Reverse with step size
fun main(args: fun main(args:
Array<String>) Array<String>)
{ {
for (item in 5 downTo 1 ) for (item in 5 downTo 1
{ step 2 ) {
println(item) println(item)
} }
} }
Iterating over a List
When only elements need to When both element and index of
be accessed the element need to be accessed

fun main() fun main()


{ {
val fruits = listOf("Apple", val fruits = listOf("Apple",
"Banana", "Cherry") "Banana", "Cherry")
for (fruit in fruits) { for (index in fruits.indices) {
println("Fruit: $fruit") println("Fruit at index
$index is ${fruits[index]}")
}
}
}
}
‘While’ loop

• While loop repeatedly fun main()


executes a block of code {
as long as the specified
condition is true. var i = 5
• Syntax: while (i > 0) {
println("value is: $i")
i--
}
}
// Think what will happen if counter
is incremented instead of
decrementing
// Try to change condition to i>5
do- while loop

• Do-while loop executes a fun main()


block of code once before {
checking the condition,
and then repeats the loop var i = 5
as long as the condition is do {
true. println("value: $i")
• Syntax: i--
}
while (i > 5) }
// even though the condition i>5
is false since beginning but still
loop executes once, this is basic
diff between while and do-while
loop
Real life application

Write a Kotlin program that simulates a simple banking system.


In this system, a user can repeatedly withdraw money from
their account until they decide to stop. Implement the following
features:
1.Initial Balance: Start with a predefined account balance
(e.g., 1000).
2.Withdrawal Process: Prompt the user to enter an amount
to withdraw.
a) If the entered amount is greater than the current balance, print a
message indicating insufficient funds.
b) If the entered amount is within the balance, deduct it from the
balance and print the new balance.
3.Continue Prompt: After each withdrawal, ask the user if
they want to make another withdrawal (yes/no).
4.Termination: When the user inputs "no", print a thank you
message and terminate the program.
fun main() else {
{ println("Insufficient
var bal = 1000 balance!")
var withdraw: Int }
var cont: String println("Do you want to make
another withdrawal? (yes/no):
do {
")
println("Your current balance
is: $bal") cont = readLine() ?: "no" }
println("Enter amount to while(cont.equals("yes",
withdraw: ") ignoreCase = true))
withdraw = println("Thank you for
readLine()?.toInt() ?: 0 using our service!")
if (withdraw <= bal) { }
bal -= withdraw
println("Withdrawal
successful! New balance:
$bal")
}
Functions in Kotlin
• Functions are reusable blocks of code that
perform a specific task. They help in reducing
code duplication and improving readability and
maintainability
• Functions are also known as methods or
subroutines
• Functions can take input (parameters) and return
output (return type)
• Syntax :

• Note that parameters and return type are


optional
Built-in Functions User defined functions

Kotlin provides a fun demo()


number of built-in {
functions to provide println("Hello,
basic functionality World!")
•print() }
•println()
fun main() {
•str.length()
•readline() demo()
•touppercase() }
•tolowercase ()
•listof ()
Functions Based on types of
arguments
Default Arguments Without default Arguements

fun sum(a:Int=10, fun sum(a:Int, b:Int)


b:Int=20) {
{ val c=a+b
val c=a+b println(c)
println(c) }
} fun main() {
fun main() { sum(20,50)
sum(20,50) sum() //this line will give
sum() error
} }
Returning values from a
function
• It is optional for a Kotlin fun main(args:
function to return a value. Array<String>) {
• o return a value, use val a = 10
the return keyword val b = 20
• return type is specified val result = sum(a, b)
after the function's
parentheses println( result )
• If a function does not }
return a useful value, its fun sum(a:Int, b:Int):Int{
return type by default is val x = a + b
referred to as Unit.
return x
}
Create a function to convert
temperatures from Celsius to
Fahrenheit and vice versa.
//Convert Celsius to Fahrenheit // Convert to Double, handling null and
invalid input cases
fun CtoF(celsius: Double): Double { val celsius = celsiusInput?.toDoubleOrNull()
return celsius * 9 / 5 + 32 val fahrenheit =
} fahrenheitInput?.toDoubleOrNull()

if (celsius != null) {
// Function to convert Fahrenheit to println("$celsius°C is equal to $
Celsius {CtoF(celsius)}°F")
fun FtoC(fahrenheit: Double): Double } else {
{ println("Invalid input for Celsius.")
return (fahrenheit - 32) * 5 / 9 }
}
if (fahrenheit != null) {
println("$fahrenheit°F is equal to $
fun main() { {FtoC(fahrenheit)}°C")
// Read and convert input values } else {
safely println("Invalid input for Fahrenheit.")
}
val celsiusInput = readLine()
}
val fahrenheitInput = readLine()
Class in Kotlin
• A class is a blueprint
for creating objects.
• Kotlin classes are
declared using
keyword class.
• Kotlin class has a
class header which
specifies its type
parameters,
constructor etc.
class Student
{
fun result()
{
println("Pending
")
}
}
fun main()
{
var s1= Student()
s1.result()
}
Primary and Secondary Constructors
• The primary constructor • A secondary constructor
is a simple, concise way is an additional way to
to initialize a class. It’s create an object. It’s
defined right after the useful when you need to
class name. set up the object with
• The primary constructor different parameters or
is used when you want to extra logic.
set up properties as soon • The secondary
as the object is created. constructor is used when
you need more flexibility
in how objects are
created.
class Person {
var name:
String fun intro()
var age:Int {
println("my name is $name and
constructor(x: age is $age")
String,y:Int) { }
this.name = x }
this.age = y fun main()
} {
var a=Person("Riya",22)
constructor(x:String a.intro()
){ var b=Person()
this.name=x b.intro()
this.age=0 var c=Person("Heena")
} c.intro()
constructor() {
this.name="Ra }
hul"
this.age=32
}
Using Primary Constructor

class Person(var name:String,


var age:Int) {
fun main()
{
constructor(x:String) : this() {
var
this.name=x a=Person("Riya",22)
this.age=0 a.intro()
} var b=Person()
constructor() : this("rahul", b.intro()
50) var
fun intro() c=Person("Heena")
{
c.intro()
println("my name is $name
and age is $age")
} }
}
Inheritance in kotlin

• Inheritance is a feature of object-oriented programming


that allows a new class (derived class) to inherit
properties and methods from an existing class (base
class). This promotes code reuse and establishes a
hierarchical relationship between classes.
• The class whose properties and methods are inherited
by another class is called base class
• To inherit a class, it should be marked as ‘open’
• The class that inherits properties and methods from the
base class is called derived class
• It can extend the functionality of the base class by
adding new properties and methods or by overriding
existing ones
• Syntax class DerivedClassName :
BaseClassName()
{
fun area():Double {
return a * b
}
open fun display() {
println("area of rectangle with dimensions $a
* $b is ${area()} ")
}
}
class Square(side: Double) : Rectangle(side, side)
{
override fun display() {
println("area of square with side $a is $
{area()}")
}
}
fun main() {
val myRectangle = Rectangle(4.0, 5.0)
myRectangle.display()
val mySquare = Square(3.0)
mySquare.display()
}
Interface in kotlin
interface Shape{
fun area():Double
}
open class Rectangle(val a: Double, val b: Double):
Shape{
override fun area():Double {
return a * b
}
open fun display() {
println("area of rectangle with dimensions $a * $b
is ${area()} ")
}
}
class Square(side: Double) : Rectangle(side, side) {
override fun display() {
println("area of square with side $a is ${area()}")
}
}
fun main() {
val myRectangle = Rectangle(4.0, 5.0)
myRectangle.display()
val mySquare = Square(3.0)
mySquare.display()
}
Recursive Function
fun factorial(n: Int): Int {
return if (n <= 1) 1 else n *
factorial(n - 1)
}
fun main()
{
println("enter the number to find
factorial")
var y:Int= readln().toInt()
var x=factorial(y)
print(x)
}
Recursive function

import java.math.BigInteger

fun factorial(n: Int): BigInteger {


return if (n == 1) BigInteger.ONE else
BigInteger.valueOf(n.toLong()).multiply(factorial(n - 1))
}
fun main()
{
println("enter the number to find factorial")
var y:Int= readln().toInt()
var x=factorial(y)
print(x)
}

You might also like