0% found this document useful (0 votes)
23 views9 pages

Unit 1

Unit 1 covers the introduction to Kotlin, its benefits, and installation of the IntelliJ IDEA IDE. It includes topics on control flow statements, null safety, functions with default and named arguments, object-oriented programming concepts, and collections in Kotlin. The unit provides examples and explanations for each concept to facilitate understanding and practical application.

Uploaded by

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

Unit 1

Unit 1 covers the introduction to Kotlin, its benefits, and installation of the IntelliJ IDEA IDE. It includes topics on control flow statements, null safety, functions with default and named arguments, object-oriented programming concepts, and collections in Kotlin. The unit provides examples and explanations for each concept to facilitate understanding and practical application.

Uploaded by

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

Unit 1  Introduction of Kotlin,

 Benefits of using Kotlin,


 Installation of IntelliJ IDEA IDE,
 Use of Kotlin, REPL to practice basic expressions,
 Control flow statements, Null safety in kotlin.
 Creating and calling functions with default and named arguments,
 passing functions as arguments to other functions,
 Writing simple lambdas.
 Introduction to object oriented programming in kotlin,
 Classes and objects,
 Constructors, Visibility modifiers,
 Subclasses and inheritance, Interfaces,
 Data classes, Singleton class enums, pairs, triples and collections in
kotlin.
 put it in index formattiing

Unit 1 :
1. Introduction of Kotlin:

Kotlin is a modern, statically-typed programming language that runs on the Java Virtual Machine
(JVM) and is designed to be fully interoperable with Java. It is known for its concise syntax,
safety features, and modern approach to programming. Kotlin is used for Android app
development, backend development, and more.

Example:

fun main() {
println("Hello, Kotlin!")
}

2. Benefits of using Kotlin:

Kotlin has several advantages over Java:

 Concise Syntax: Less code to write compared to Java, reducing boilerplate.


 Interoperability: Kotlin can work seamlessly with Java code.
 Null Safety: Built-in features that help prevent null pointer exceptions.
 Smart Casts: Automatically casts variables to the correct type when needed.
 Functional Programming: Supports functional programming features like higher-order
functions.
Example: In Kotlin, you can do things like this more concisely than Java:

val list = listOf("apple", "banana", "cherry")


val filtered = list.filter { it.startsWith("b") }

3. Installation of IntelliJ IDEA IDE:

To start using Kotlin, you need an Integrated Development Environment (IDE). IntelliJ IDEA is
one of the most popular IDEs for Kotlin development.

 Step 1: Download IntelliJ IDEA from the official website.


 Step 2: Install it by following the setup instructions.
 Step 3: After installation, open IntelliJ IDEA and create a new Kotlin project.

Once installed, you can use IntelliJ IDEA to write, compile, and run Kotlin programs.

4. Use of Kotlin:

Kotlin is used in various domains:

 Android Development: It is the preferred language for Android apps.


 Web Development: Kotlin can be used for backend development with frameworks like
Ktor.
 Data Science: Kotlin can be used for building data-driven applications.
 Desktop and Server-Side Applications: Kotlin can run on any platform where Java can
run.

Example: A simple Android app written in Kotlin:

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}

5. REPL to practice basic expressions:

REPL stands for Read-Eval-Print Loop, a tool that allows you to write and test Kotlin code
interactively. It evaluates expressions and prints results immediately. It’s useful for learning and
experimenting with Kotlin code.

 To use REPL in IntelliJ IDEA: Open the Kotlin REPL window and start typing Kotlin
expressions.

Example: In the REPL, you can test basic expressions like:


println(5 + 3) // Outputs 8

6. Control flow statements:

Control flow statements in Kotlin help you control the flow of the program, like if-else
conditions and loops.

 If-else:

val number = 10
if (number > 5) {
println("Greater than 5")
} else {
println("Less than or equal to 5")
}

 When: A powerful alternative to the switch statement.

val number = 2
when (number) {
1 -> println("One")
2 -> println("Two")
else -> println("Other")
}

 For loop: To iterate over a range or collection.

for (i in 1..5) {
println(i)
}

 While loop: Repeats a block of code as long as the condition is true.

var count = 1
while (count <= 5) {
println(count)
count++
}

7. Null safety in Kotlin:

Kotlin handles null references carefully to prevent NullPointerException. A variable can


either hold a null value or not, and the compiler enforces this.

 Non-nullable variable:

var name: String = "John" // Cannot be null

 Nullable variable (using ?):


var name: String? = null // Can be null

 Safe calls (?.):

val length = name?.length // Returns null if 'name' is null

 Elvis operator (?:):

val length = name?.length ?: 0 // If 'name' is null, return 0

8. Creating and calling functions with default and named arguments:

Kotlin allows functions to have default values for parameters, and named arguments for clarity.

 Default Arguments:

fun greet(name: String = "Guest") {


println("Hello, $name!")
}
greet() // Outputs: Hello, Guest!
greet("Alice") // Outputs: Hello, Alice!

 Named Arguments:

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


println(a + b)
}
sum(a = 3, b = 4) // Named arguments make the call clearer

9. Passing functions as arguments to other functions:


Kotlin allows you to pass functions as parameters. This feature is useful for higher -order
functions.

 Example:

fun operateOnNumbers(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}

val sum = { x: Int, y: Int -> x + y }


println(operateOnNumbers(3, 4, sum)) // Outputs: 7

10. Writing simple lambdas:

A lambda expression is a concise way to define anonymous functions in Kotlin. Lambdas are
often used with higher-order functions like map, filter, etc.

 Example:
val square = { x: Int -> x * x }
println(square(5)) // Outputs: 25

Lambdas are often passed to functions as arguments:

val numbers = listOf(1, 2, 3, 4, 5)


val doubled = numbers.map { it * 2 } // Doubles each number
println(doubled) // Outputs: [2, 4, 6, 8, 10]

Here’s a breakdown of each heading in Object-Oriented Programming (OOP) in Kotlin with


simple definitions, examples, and types:

11. Introduction to Object-Oriented Programming (OOP) in Kotlin:

Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes.
In Kotlin, OOP is used to organize and structure code. It makes code more modular, reusable,
and easier to maintain. OOP principles are based on 4 main concepts: Encapsulation,
Abstraction, Inheritance, and Polymorphism.

 Example: In Kotlin, classes are blueprints that define objects. Objects represent instances
of these classes.

12. Classes and Objects:

 Class: A class is a blueprint or template for creating objects. It defines properties and
methods that an object can have.
 Object: An object is an instance of a class. When you create an object, it uses the class as
its blueprint.

Example:

class Car(val brand: String, val model: String) {


fun drive() {
println("Driving the $brand $model")
}
}

val myCar = Car("Toyota", "Corolla") // Object creation


myCar.drive() // Calling method on the object

13. Constructors:

A constructor is a special function in a class that is called when an object is created. It initializes
the object with values.

 Primary Constructor: Defined directly in the class declaration.


 Secondary Constructor: Defined inside the class with the constructor keyword.
Example:

class Car(val brand: String, val model: String) { // Primary constructor


fun start() {
println("$brand $model is starting.")
}
}

val myCar = Car("Ford", "Focus") // Primary constructor


myCar.start()
class Car {
var brand: String
var model: String

constructor(brand: String, model: String) { // Secondary constructor


this.brand = brand
this.model = model
}
}

val myCar = Car("Honda", "Civic") // Using secondary constructor

14. Visibility Modifiers:

Visibility modifiers define the accessibility of classes, methods, and properties. Kotlin has the
following visibility modifiers:

 public: The default modifier; accessible from anywhere.


 private: Accessible only within the class.
 protected: Accessible in the class and its subclasses.
 internal: Accessible within the same module.

Example:

class Car {
private val engine = "V8" // Only accessible within the Car class

fun start() {
println("Engine type: $engine")
}
}

15. Subclasses and Inheritance:

Inheritance allows a class (child or subclass) to inherit properties and methods from another class
(parent or superclass). This promotes reusability.

 Superclass (Parent class): The class being inherited from.


 Subclass (Child class): The class that inherits from the superclass.

Example:
open class Animal(val name: String) { // Parent class
fun speak() {
println("$name makes a sound")
}
}

class Dog(name: String) : Animal(name) { // Subclass inheriting from Animal


fun bark() {
println("$name barks")
}
}

val dog = Dog("Buddy")


dog.speak() // Inherited method
dog.bark() // Subclass method

16. Interfaces:

An interface defines a contract of methods that a class must implement. It’s similar to a class but
can’t have a body for the methods. A class can implement multiple interfaces.

Example:

interface Drivable {
fun drive()
}

class Car : Drivable {


override fun drive() {
println("Car is driving")
}
}

val car = Car()


car.drive() // Calls the drive method from Drivable interface

17. Data Classes:

A data class is a special class in Kotlin that automatically provides useful methods such as
equals(), hashCode(), and toString() for its properties. It is primarily used to store data.

Example:

data class Car(val brand: String, val model: String)

val myCar = Car("Toyota", "Corolla")


println(myCar) // Automatically calls toString() -> Car(brand=Toyota,
model=Corolla)

18. Singleton Class Enums:


 Singleton Class: A class that can have only one instance. It ensures that a class has only
one object, and it provides a global access point to that object.

Example:

object Singleton {
val name = "Unique Instance"
}
println(Singleton.name) // Accessing the singleton object

 Enum: A special class that represents a group of constants. It’s useful when you have a
predefined set of values, like days of the week or seasons.

Example:

enum class Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY,


SUNDAY }

val today = Day.MONDAY


println(today) // Output: MONDAY

19. Pairs:

A Pair is a simple class that holds two values. It's often used when you want to return two
related values from a function.

Example:

val pair = Pair("John", 30)


println(pair.first) // John
println(pair.second) // 30

20. Triples:

A Triple holds three values, similar to a Pair but with one additional value. It's useful when you
need to return three related values.

Example:

val triple = Triple("John", 30, "Engineer")


println(triple.first) // John
println(triple.second) // 30
println(triple.third) // Engineer

11. Collections in Kotlin:

Collections are data structures that hold multiple elements. Kotlin has three main types of
collections:
 List: Ordered collection of elements. It can be mutable or immutable.
o MutableList: Allows modification (add/remove elements).
o List: Immutable; can't be modified after creation.

Example:

val list = listOf(1, 2, 3) // Immutable List


val mutableList = mutableListOf(1, 2, 3) // Mutable List
mutableList.add(4)

 Set: Collection of unique elements (no duplicates).


o MutableSet: Allows modification.
o Set: Immutable.
 Map: Collection of key-value pairs.
o MutableMap: Allows modification.
o Map: Immutable.

Example:

val map = mapOf("a" to 1, "b" to 2)


val mutableMap = mutableMapOf("a" to 1, "b" to 2)
mutableMap["c"] = 3

You might also like