0% found this document useful (0 votes)
3 views

Kotlin Notes (1)

The document provides an overview of programming, including its definition, uses, and types of programming languages, specifically focusing on Kotlin. It explains the concepts of compilers and interpreters, as well as basic syntax, variables, data types, operators, control flow structures, loops, arrays, functions, and object-oriented programming in Kotlin. Additionally, it highlights Kotlin's compatibility with Java and its applications in various fields such as mobile and web development.

Uploaded by

karanamraju000
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Kotlin Notes (1)

The document provides an overview of programming, including its definition, uses, and types of programming languages, specifically focusing on Kotlin. It explains the concepts of compilers and interpreters, as well as basic syntax, variables, data types, operators, control flow structures, loops, arrays, functions, and object-oriented programming in Kotlin. Additionally, it highlights Kotlin's compatibility with Java and its applications in various fields such as mobile and web development.

Uploaded by

karanamraju000
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 57

KOTLIN

-By Koushik Lammatha



Programming is the process of creating
What is instructions for a computer to execute.
It involves writing, testing, and
Programmi maintaining sets of instructions, known
ng as code, that tell a computer how to
perform specific tasks or solve
particular problems
▪ Programming has numerous uses across various
fields and industries. Some of the primary uses
of programming include:
1.Software Development
2.Web Development
What is the 3.Data Analysis and Machine Learning
use of 4.Automation

programmi 5.Scientific Computing


6.Embedded Systems
ng 7.Game Development
• Cybersecurity
1.Financial Analysis and Trading
2.Artificial Intelligence and Robotics
1.High-Level Languages: These languages
are closer to human languages and are easier
to read and write. Examples include Python,

Types of Java, C++, and JavaScript.


2.Low-Level Languages: These languages
Programmi are closer to machine code and are more
ng difficult for humans to read and write directly.

Languages They provide more direct control over


hardware but are less portable. Examples
include Assembly language and Machine
code.
▪ A compiler is a specialized program that translates
high-level source code written in a programming
language into machine code that a computer can
execute directly. It performs several stages of
analysis and transformation, including lexical
analysis, syntax analysis, semantic analysis,

Compil optimization, and code generation. The compiler


ensures that the source code is syntactically

er
correct and adheres to the rules of the
programming language. Once the translation
process is complete, the resulting machine code
can be executed by the computer's processor.
Compilers are essential tools in software
development, enabling programmers to write code
in familiar languages while allowing computers to
understand and execute it efficiently.
▪ An interpreter is a program that directly executes
source code written in a high-level programming
language without the need for prior translation into
machine code. It reads the source code line by line
and translates each line into machine code
instructions or intermediate code on-the-fly. The
interpreter then executes these instructions
immediately, allowing the program to run without

Interpreter generating a separate executable file. This


approach makes interpretation slower than
compilation, as the source code must be analyzed
and translated each time the program is run.
However, interpreters offer advantages such as
portability and ease of debugging, as they can
provide immediate feedback on errors and allow for
dynamic code execution. Examples of interpreted
languages include Python, JavaScript, and Ruby.

Translation Process:
1. Compiler: Translates the entire source code into machine code or intermediate code before
execution.
2. Interpreter: Translates source code line-by-line or statement-by-statement and executes it
immediately without creating an intermediate representation.

1. Execution:
1. Compiler: Produces a standalone executable file that can be executed independently of the
original source code.
2. Interpreter: Executes the source code directly without generating an independent executable
file.

COMPLIER 2. Performance:
• Compiler: Typically produces faster-executing code since it optimizes the entire program

VS •
before execution.
Interpreter: Generally slower as it translates and executes code line-by-line or statement-by-

INTERPRET
statement.

3. Debugging:

ER
1. Compiler: Debugging can be more challenging as errors may only be detected during
compilation or runtime.
2. Interpreter: Easier to debug as errors are reported immediately at the line causing the issue.

4. Portability:
1. Compiler: Generates machine-specific code, so the compiled executable may not run on
different architectures without recompilation.
2. Interpreter: Source code is generally portable, as long as the interpreter is available for the
target platform.

• Examples:
• Compiler: Examples include GCC (GNU Compiler Collection), Microsoft Visual C++, and LLVM.
1. Interpreter: Examples include Python, JavaScript (in web browsers), and Ruby.
▪ Kotlin is a modern, trending programming language
that was released in 2016 by JetBrains.
▪ It has become very popular since it is compatible with
Java (one of the most popular programming languages
out there), which means that Java code (and libraries)
can be used in Kotlin programs.
What is ▪ Kotlin is used for:
Kotlin • Mobile applications (specially Android apps)
• Web development
• Server side applications
• Data science
• And much, much more!
• Kotlin is fully compatible with Java
• Kotlin works on different platforms (Windows, Mac,
Linux, Raspberry Pi, etc.)
• Kotlin is concise and safe
Use of • Kotlin is easy to learn, especially if you already
Kotlin know Java
• Kotlin is free to use
• Big community/support
▪ fun main()
▪ {
▪ println("Hello World")
▪ }
▪ The fun keyword is used to declare a function. A function is a
block of code designed to perform a particular task. In the
Kotlin example above, it declares the main() function.

Syntax ▪ The main() function is something you will see in every Kotlin
program. This function is used to execute code. Any code
inside the main() function's curly brackets {} will
be executed.
▪ For example, the println() function is inside
the main() function, meaning that this will be executed.
The println() function is used to output/print text, and in our
example it will output "Hello World".
▪ fun main()
▪{
▪ println("Hello World!")
Some ▪ println("I am learning Kotlin.")
Examples ▪ println("It is awesome!")
▪ println(3 + 3)
▪}
▪ Single-line comments starts with two forward
slashes (//).
▪ Any text between // and the end of the line is

Single Line ignored by Kotlin (will not be executed).


▪ This example uses a single-line comment before a
Comments line of code:
▪ // This is a comment
▪ println("Hello World")
▪ Multi-line comments start with /* and ends with */.
▪ Any text between /* and */ will be ignored by Kotlin.
▪ This example uses a multi-line comment (a
Multi Line comment block) to explain the code:
Comments ▪ /* The code below will print the words Hello World
to the screen, and it is amazing */
▪ println("Hello World")
▪ Variables are containers for storing data values.
▪ To create a variable, use var or val, and assign a
value to it with the equal sign (=):

Variables ▪Syntax
▪ var variableName = value
▪ val variableName = value
▪ var name = "John"
▪ val birthyear = 1975
▪ println(name) // Print the value of name
Example println(birthyear) // Print the value of birthyear
▪ The difference between var and val is that
variables declared with the var keyword can be
changed/modified, while val variables cannot.
▪ val name = "John"
▪ println("Hello " + name)
▪ val firstName = "John ”
▪ val lastName = "Doe"

Display ▪ val fullName = firstName + lastName

Variables ▪ println(fullName)
▪ val x = 5 val
▪y=6
▪ println(x + y)
▪ // Print the value of x + y
▪ val myNum = 5 // Int
▪ val myDoubleNum = 5.99 // Double

Data Types ▪ val myLetter = 'D' // Char


▪ val myBoolean = true // Boolean
▪ val myText = "Hello" // String
Operators are used to perform operations on variables and
values.
Kotlin Operators The value is called an operand, while the operation (to be
performed between the two operands) is defined by
an operator:
Operand Operator Operand

100 + 50
Table 1
OpeNam Description Exa
ratoe mpl
Arithmetic r
+ Additi Adds
e
x+
Operators on together two y
values
- Subtr Subtracts x-
actio one value y
n from another
* Multi Multiplies x*
plicat two values y
ion
/ Divisi Divides one x /
on value from y
another
% Modu Returns the x %
lus division y
Operator Example Same As

Assignment = x=5 x=5

Operators += x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3
Operator Name Example

Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal x >= y


to

<= Less than or equal to x <= y


Operator Name Description Example

&& Logical and Returns true if both x < 5 && x <

Logical statements are true 10

Operators || Logical or Returns true if one of


the statements is true
x < 5 || x < 4

! Logical not Reverse the


result, returns
false if the result
is true
Kotlin supports the usual logical conditions from mathematics:
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
If - Else • Greater than or equal to: a >= b
• Equal to a == b
• Not Equal to: a != b
• You can use these conditions to perform different actions for
different decisions.
if (condition) {
// block of code to be executed if the condition is true
}

Syntax •Example
if (20 > 18) {
println("20 is greater than 18")
}
val x = 20
val y = 18
Example if (x > y) {
println("x is greater than y")
}
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

If-else val time = 20


if (time < 18) {
println("Good day.")
} else {
println("Good evening.")
}
// Outputs "Good evening."
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
Else-if condition2 is true
} else {
// block of code to be executed if the condition1 is false and
condition2 is false
}
val time = 22
if (time < 10) {
println("Good morning.")
} else if (time < 20) {
Example println("Good day.")
} else {
println("Good evening.")
}
// Outputs "Good evening."
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:


val day = 4

val result = when (day) {


1 -> "Monday"
When 2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid day."
}
println(result)
▪ fun main() {
▪ for(i in 1..10){
▪ println(i)
▪ }
▪ for(i in 1 until 5){
▪ println(i)

For Loop }
▪ for(i in 5 downTo 1){
▪ println(i)
▪ }
▪ for(i in 1..15 step 2){
▪ println(i)
▪ }
▪}
Loops can execute a block of code as long as a specified
condition is reached.

While Loop Loops are handy because they save time, reduce errors, and
they make code more readable.
while (condition) {
// code block to be executed
}
var i = 0
while (i < 5) {
Example println(i)
i++
}
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.
Do-while do {
// code block to be executed
}
while (condition);
var i = 0
do {
Example println(i)
i++
}
while (i < 5)
Arrays are used to store multiple values in a single variable,
instead of creating separate variables for each value.
Arrays To create an array, use the arrayOf() function, and place the
values in a comma-separated list inside it:
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
Accessing You can access an array element by referring to the index
number, inside square brackets.
Elements In this example, we access the value of the first element in cars:
In an Array val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
println(cars[0])
Changing ▪To change the value of a specific element, refer to
Elements the index number:
In an array cars[0] = "Opel"
Array Length or
Size val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
println(cars.size)
Checking val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
if ("Volvo" in cars) {
Elements println("It exists!")
} else {
In Array println("It does not exist.")
}
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
Loop Through for (x in cars) {
println(x)
Array }
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 Functions are used to perform certain actions, and they are
In Kotlin also known as methods.
fun myFunction() {
println("I just got executed!")
}
fun main() {
Call myFunction() // Call myFunction
}
A Function
fun myFunction(fname: String) {
println(fname + " Doe")
Function }

Parameters fun main() {


myFunction("John")
In Kotlin myFunction("Jane")
myFunction("George")
}
fun myFunction(x: Int): Int {
return (x + 5)
}
Funtion Return fun main() {
VALUES var result = myFunction(3)
println(result)
}
OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or


methods that perform operations on the data, while object-
oriented programming is about creating objects that contain
both data and methods.

Kotlin OOP Object-oriented programming has several advantages over


procedural programming:
• OOP is faster and easier to execute
• OOP provides a clear structure for the programs
• OOP helps to keep the Kotlin code DRY "Don't Repeat
Yourself", and makes the code easier to maintain, modify and
debug
• OOP makes it possible to create full reusable applications
with less code and shorter development time
Everything in Kotlin is associated with classes and objects,
along with its properties and functions. For example: in real life,
a car is an object. The car has properties, such as brand,
Classes and weight and color, and functions, such as drive and brake.

Objects A Class is like an object constructor, or a "blueprint" for creating


objects.
class Car {
var brand = ""
var model = ""
var year = 0
}
Creation of an // Create a c1 object of the Car class
val c1 = Car()

Object // Access the properties and add some values to it


c1.brand = "Ford"
c1.model = "Mustang"
c1.year = 1969

println(c1.brand) // Outputs Ford


println(c1.model) // Outputs Mustang
println(c1.year)
val c1 = Car()
c1.brand = "Ford"
c1.model = "Mustang"
c1.year = 1969

Mutliple Objects val c2 = Car()


c2.brand = "BMW"
c2.model = "X5"
c2.year = 1999

println(c1.brand) // Ford
println(c2.brand)
Kotlin class Car(var brand: String, var model: String, var year: Int)

Constructors fun main() {


val c1 = Car("Ford", "Mustang", 1969)
}
class Car(var brand: String, var model: String, var year: Int)

fun main() {
Example val c1 = Car("Ford", "Mustang", 1969)
val c2 = Car("BMW", "X5", 1999)
val c3 = Car("Tesla", "Model S", 2020)
}
class Car(var brand: String, var model: String, var year: Int) {
// Class function
fun drive() {
println("Wrooom!")
Class Functions }
}

or methods
fun main() {
val c1 = Car("Ford", "Mustang", 1969)

// Call the function


c1.drive()
}
class Car(var brand: String, var model: String, var year: Int) {
// Class function
fun drive() {
println("Wrooom!")
}

// Class function with parameters


fun speed(maxSpeed: Int) {
println("Max speed is: " + maxSpeed)
Example }
}

fun main() {
val c1 = Car("Ford", "Mustang", 1969)

// Call the functions


c1.drive()
c1.speed(200)
}
Kotlin Inheritance (Subclass and
Superclass)
Inheritance In Kotlin, it is possible to inherit class properties and functions
from one class to another. We group the "inheritance
concept" into two categories:
• subclass (child) - the class that inherits from another class
• superclass (parent) - the class being inherited from
// Superclass
open class MyParentClass {
val x = 5
}

// Subclass
class MyChildClass: MyParentClass() {
fun myFunction() {
Inheritance println(x) // x is now inherited from the superclass
}
}

// Create an object of MyChildClass and call myFunction


fun main() {
val myObj = MyChildClass()
myObj.myFunction()
}
▪Interfaces in Kotlin can contain declarations of
abstract methods, as well as method
implementations.
Interfaces interface MyInterface {
fun bar()
fun foo() {
// optional body
}
}
interface Bank{
var balance:Double
fun deposit(depositAmount:Double)
fun withDraw(withdrawAmount:Double)
}

class Transactions:Bank{
override var balance: Double = 1000.0

Example override fun deposit(depositAmount: Double)


{
balance+=depositAmount
}

override fun withDraw(withdrawAmount:


Double) {
balance -= withdrawAmount
}
}
The End
-by Koushik Lammatha

You might also like