UNIT-1
KOTLIN BASICS
• KOTLIN is a cross platform, statically typed,
general purpose programming
language with type inference.
• KOTLIN is designed to interoperate fully with
java but type inference allows its syntax to be
more concise.
• KOTLIN is sponsored by JetBrains and Google
through the Kotlin Foundation.
Using Kotlin over Java language in Android
• The most important reason for
introducing Kotlin to Android advancement was
to decrease the number of lines of code and
make development more convenient.
• Everything that can be done utilizing Java can be
done utilizing Kotlin for Android development.
• Despite all the differences between the two
languages, Java and Kotlin are
100% interoperable.
• You can call Kotlin code from Java, and you
can call Java code from Kotlin.
• So it’s possible to have Kotlin and Java classes
side-by-side within the same project, and
everything will still compile.
Features of Kotlin
• Kotlin is a modern programming language that helps
developers be more productive.
• For example, Kotlin allows you to be more concise and
write fewer lines of code for the same functionality
compared to other programming languages.
• Apps that are built with Kotlin are also less likely to crash,
resulting in a more stable and robust app for users.
• Essentially, with Kotlin, you can write better Android apps
in a shorter amount of time.
• As a result, Kotlin is gaining momentum in the industry and
is the language that the majority of professional Android
developers use.
Sample code
Open kotlin playground online
Sample code-
• fun main() {
println("Hello, world!")
}
• Note-Function names should follow the camel
case convention
Relevant style guide recommendations Kotlin :
• Function names should be in camel case and
should be verbs or verb phrases.
• Each statement should be on its own line.
• The opening curly brace should appear at the
end of the line where the function begins.
• There should be a space before the opening
curly brace.
• The function body should be indented.
• The closing curly brace is on its own line after
the last line of code in the function body. The
closing brace should line up with
the fun keyword at the beginning of the
function
Variable declaration
• fun main() {
val count: Int = 2
println(count)
}
Updated version-
• fun main() {
val unreadCount = 5
val readCount = 100
println("You have ${unreadCount + readCount}
total messages in your inbox.")
}
comments
• /*
* This program displays the number of messages
* in the user's inbox.
*/
fun main() {
// Create a variable for the number of unread messages.
var count = 10
println("You have $count unread messages.")
// Decrease the number of messages by 1.
count--
println("You have $count unread messages.")
}
Classes & objects
• In Kotlin, to declare a class you basically write-
• class ClassName(Parameter-Declaration1, Parameter-
Declaration2, ...) { [Class-Body] }
Let us examine its parts:
• ClassName: This is the name of the class. It must not contain
spaces, and in Kotlin by convention you should use
CamelCase notation as in EmployeeRecord.
• Parameter-Declaration:
• Variable-Name:Variable-Type: An example
would be userName: String Use this to pass a
parameter usable for instantiating a class. This
happens inside a special construct called an
init{} block. We’ll talk about that initialization
later.
• val Variable-Name:Variable-Type (e.g., val
userName: String): Use this to pass a usable
parameter from inside the init{} block, but also
define a nonmutable (unchangeable) property.
This parameter is thus used to directly set parts
of the object’s state.
• var Variable-Name:Variable-Type (e.g., var
userName: String): Use this to pass a usable
parameter from inside the init() function, but also
to define a mutable (changeable) property for
setting parts of the object’s state.
• [Class-Body]: This is a placeholder for any
number of functions and additional
properties, and also init { ... } blocks worked
through while instantiating a class.
• In addition, you can also have secondary
constructors and companion objects.
Functions
The Unit type
• By default, if you don't specify a return type, the default
return type is Unit.
• Unit means the function doesn't return a value. Unit is
equivalent to void return types in other languages (void in
Java and C; Void/empty tuple () in Swift; None in Python,
etc.).
• Any function that doesn't return a value implicitly
returns Unit. You can observe this by modifying your code
to return Unit.
• In the function declaration for birthdayGreeting(), add a
colon after the closing parenthesis and specify the return
type as Unit.
• fun main() {
birthdayGreeting()
}
fun birthdayGreeting(): Unit {
println("Happy Birthday, Rover!")
println("You are now 5 years old!")
}
• Not returning anything
Return a String from birthdayGreeting()
• To demonstrate how a function can return a
value, you'll modify
the birthdayGreeting() function to return a
string, rather than simply print the result.
• Replace the Unit return type with String.
• fun main() {
• val greeting = birthdayGreeting()
• println(greeting)}
• fun birthdayGreeting(): String {
• val nameGreeting = "Happy Birthday, Rover!"
• val ageGreeting = "You are now 5 years old!"
• return "$nameGreeting\n$ageGreeting"
• }
Adding parameters
• As you've seen, when you call println(), you can
include a string within the parentheses or pass a
value to the function.
• You can do the same with
your birthdayGreeting() function. However, you
first need to add
a parameter to birthdayGreeting().
• A parameter specifies the name of a variable and
a data type that you can pass into a function as
data to be accessed inside the function.
• fun birthdayGreeting(name: String): String {
val nameGreeting = "Happy Birthday, $name!"
val ageGreeting = "You are now 5 years old!"
return "$nameGreeting\n$ageGreeting"
}
• fun main() {
println(birthdayGreeting("Rover"))
println(birthdayGreeting("Range"))
}
• Note-Unlike in some languages, such as Java,
where a function can change the value passed
into a parameter, parameters in Kotlin are
immutable.
Adding Multiple Parameters
• fun birthdayGreeting(name: String, age: Int):
String {
val nameGreeting = "Happy Birthday, $name!"
val ageGreeting = "You are now $age years
old!"
return "$nameGreeting\n$ageGreeting"
}
• fun main() {
println(birthdayGreeting("Rover", 5))
println(birthdayGreeting("Rex", 2))
}
Default Arguments
• Function parameters can also specify default
arguments.. When you call a function, you can
choose to omit arguments for which there is a
default vaue provided.
• To add a default argument, you add the
assignment operator (=) after the data type
for the parameter and set it equal to a value.
Modify your code to use a default argument.
In the birthdayGreeting() function, set the name parameter to the
default value "Rover".
• fun birthdayGreeting(name: String = "Rover", age: Int): String {
return "Happy Birthday, $name! You are now $age years old!"
}
• In the first call to birthdayGreeting() for Rover in main(), set
the age named argument to 5. Because the age parameter is
defined after the name, you need to use the named argument age.
• Without named arguments, Kotlin assumes the order of arguments
is the same order in which parameters are defined. The named
argument is used to ensure Kotlin is expecting an Int for
the age parameter.
• println(birthdayGreeting(age = 5))
println(birthdayGreeting("Rex", 2))
The first call to the birthdayGreeting() function prints "Rover"
as the name because you never specified the name. The
second call to birthdayGreeting() still uses the Rex value,
which you passed in for the name.
Output-
• Happy Birthday, Rover!
• You are now 5 years old!
• Happy Birthday, Rex!
• You are now 2 years old!
• Remove the name from the second call to
the birthdayGreeting() function. Again, because name is
omitted, you need to use a named argument for the age.
• println(birthdayGreeting(age = 5))
println(birthdayGreeting(age = 2))
Run your code and then observe that now both calls
to birthdayGreeting() print "Rover" as the name because no
name argument is passed in.
• Happy Birthday, Rover!
• You are now 5 years old!
• Happy Birthday, Rover!
You are now 2 years old!
Object & Classes
• a class is a blueprint for an object. The Kotlin runtime uses the
class, or blueprint, to create an object of that particular type. With
the abc class, you have a blueprint of what a class is. To have
an actual abc class in your program, you need to create a abc object
instance.
• The instantiation syntax starts with the class name followed by a
set of parentheses as you can see in this diagram:
• class abc {
// empty body
}
fun main() {
}
• Object is-abc()
• To use an object, you create the object and assign it to
a variable, similar to how you define a variable.
• You use the val keyword to create an immutable
variable and the var keyword for a mutable variable.
• The val or var keyword is followed by the name of the
variable, then an = assignment operator, then the
instantiation of the class object.
syntax-
• Note: When you define the variable with the val keyword
to reference the object, the variable itself is read-only, but
the class object remains mutable.
• This means that you can't reassign another object to the
variable, but you can change the object's state when you
update its properties' values.
• Instantiate the abc class as an object:
• In the main() function, use the val keyword to create a
variable named abc1 and initialize it as an instance of
the abc class:
• fun main() {
val abc1 = abc()
• class SmartDevice {
fun turnOn() {
println("Smart device is turned on.")
}
fun turnOff() {
println("Smart device is turned off.")
}
}
• fun main() {
val smartTvDevice = SmartDevice()
smartTvDevice.turnOn()
smartTvDevice.turnOff()
}
• class SmartDevice {
val name = "Android TV"
val category = "Entertainment"
var deviceStatus = "online"
fun turnOn() {
println("Smart device is turned on.")
}
fun turnOff() {
println("Smart device is turned off.")
}
}
• fun main() {
val smartTvDevice = SmartDevice()
println("Device name is: ${smartTvDevice.name}")
smartTvDevice.turnOn()
smartTvDevice.turnOff()
}
Inheritance
• Inheritance in Kotlin-
• is the process where a new class inherits the
properties of an existing class. The existing
class whose properties are inherited is known
as the superclass or base class, and the class
that inherits the members of the existing one
is known as the subclass or derived class.
• open class Superclass {
// Properties and methods of the superclass
}
class Subclass : Superclass() {
// Properties and methods of the subclass
}
• open class Superclass: This declares a superclass
named Superclass. The open keyword is used to
indicate that the class can be subclassed or extended.
By default, classes in Kotlin are considered final, which
means they cannot be inherited from unless explicitly
marked as open or abstract.
• class Subclass : Superclass(): This declares a subclass
named Subclass that inherits from the Superclass. The :
symbol indicates inheritance, and Superclass is the
name of the superclass from which Subclass inherits.
• // Superclass
• open class Vehicle(val brand: String, val year: Int) {
• fun start() {
• println("$brand vehicle started")
• }
• fun stop() {
• println("$brand vehicle stopped")
• }
• }
• // Subclass 1: Car
• class Car(brand: String, year: Int, val model: String) : Vehicle(brand, year) {
• fun drive() {
• println("$brand $model is driving")
• }
• }
• // Subclass 2: Motorcycle
• class Motorcycle(brand: String, year: Int, val type: String) : Vehicle(brand, year) {
• fun ride() {
• println("$brand $type is riding")
• }
• }
• fun main() {
• val car = Car("Toyota", 2022, "Camry")
• val motorcycle = Motorcycle("Harley-Davidson", 2021, "Sportster")
• car.start()
• car.drive()
• car.stop()
• motorcycle.start()
• motorcycle.ride()
• motorcycle.stop()
• }
• 1. Single Inheritance
open class Animal {
// ...
}
class Dog : Animal() {
// ...
}
• 2. Multiple Inheritance
interface Animal {
// ...
}
interface Vehicle {
// ...
}
class DogCar : Animal, Vehicle {
// ...
}
• 3. Hierarchical Inheritance
open class Shape {
// ...
}
class Circle : Shape() {
// ...
}
class Rectangle : Shape() {
// ...
}
• 4. Multilevel Inheritance
open class Animal {
// ...
}
class Mammal : Animal() {
// ...
}
class Dog : Mammal() {
// ...
}
5. Hybrid Inheritance
Constructors
Kotlin has two types of constructors:
• Primary Constructor
• Secondary Constructor
• A class in Kotlin can have at most one primary constructor, and one
or more secondary constructors. The primary constructor initializes
the class, while the secondary constructor is used to initialize the
class and introduce some extra logic.
• Primary Constructor
• The primary constructor is initialized in the class header, and goes
after the class name, using the constructor keyword. The
parameters are optional in the primary constructor.
class Add constructor(val a: Int, val b: Int) {
// code
}
fun main()
{
val add = Add(5, 6)
println("The Sum of numbers 5 and 6 is: ${add.c}")
}
// primary constructor
class Add constructor(a: Int,b:Int)
{
var c = a+b;
}
Init block
• The primary constructor cannot contain any code, the
initialization code can be placed in a separate initializer
block prefixed with the init keyword.
What is init block?
• It acts as an initialiser block where member variables
are initialised.
• This block gets executed whenever an instance of this
class is created.
• There can be multiple init blocks and they are called in
the order they are written inside the class.
• init blocks gets called before the constructor of this
class is called.
• class Person (val _name: String) {
• // Member Variables
var name: String
// Initializer Blocks
init{
println("This is first init block")
}
init{
println("This is second init block")
}
init{
println("This is third init block")
}
init {
this.name = _name
println("Name = $name")
}
}
fun main() {
val person = Person("Geeks")
}
• Secondary Constructor
• As mentioned above, Kotlin may have one or
more secondary constructors. Secondary
constructors allow initialization of variables
and allow to provide some logic to the class as
well. They are prefixed with
the constructor keyword.
• // main function
• fun main()
• {
• Add(5, 6)
• }
• // class with one secondary constructor
• class Add
• {
• constructor(a: Int, b:Int)
• {
• var c = a + b
• println("The sum of numbers 5 and 6 is: ${c}")
• }
• }
• fun main() {
employee(18018, "Sagnik")
employee(11011,"Praveen",600000.5)
}
class employee {
constructor (emp_id : Int, emp_name: String ) {
var id: Int = emp_id
var name: String = emp_name
print("Employee id is: $id, ")
println("Employee name: $name")
println()
}
constructor (emp_id : Int, emp_name: String ,emp_salary : Double) {
var id: Int = emp_id
var name: String = emp_name
var salary : Double = emp_salary
print("Employee id is: $id, ")
print("Employee name: $name, ")
println("Employee name: $salary")
}
}
Kotlin extension function
• Kotlin gives the programmer the ability to add
more functionality to the existing
classes, without inheriting them. This is
achieved through a feature known
as extensions.
• When a function is added to an existing class
it is known as Extension Function. To add an
extension function to a class, define a new
function appended to the classname
// A sample class to demonstrate extension functions
class Circle (val radius: Double){
// member function of class
fun area(): Double{
return Math.PI * radius * radius;
}
}
fun main(){
// Extension function created for a class Circle
fun Circle.perimeter(): Double{
return 2*Math.PI*radius;
}
// create object for class Circle
val newCircle = Circle(2.5);
// invoke member function
println("Area of the circle is ${newCircle.area()}")
// invoke extension function
println("Perimeter of the circle is ${newCircle.perimeter()}")
}