Kotlin OOP Presentation
Kotlin OOP Presentation
• fun main() {
• val person = Person("Ali", 21)
• person.greet()
• }
Function in Kotlin
• A function in Kotlin is defined using the 'fun' keyword.
• Example:
• fun add(a: Int, b: Int): Int {
• return a + b
• }
• fun main() {
• val sum = add(5, 3)
• println("Sum: $sum")
• }
Constructor in Kotlin
• Kotlin has primary and secondary constructors.
• The primary constructor is part of the class header, while secondary constructors are inside
the class body.
• Example:
• class Student(val name: String, val age: Int) { // Primary constructor
• init {
• println("Student initialized with name: $name and age: $age")
• }
• // Secondary constructor
• constructor(name: String) : this(name, 18) {
• println("Secondary constructor called")
• }
• }
• fun main() {
• val student1 = Student("Ali", 21)
Object in Kotlin
• In Kotlin, an object can be created using the 'object' keyword for a singleton pattern or for
creating an anonymous object.
• Example of Singleton:
• object Database {
• val name = "MyDatabase"
• fun connect() {
• println("Connecting to $name")
• }
• }
• fun main() {
• Database.connect()
• }
Dialog Box in Kotlin
• A dialog box in Android can be created using AlertDialog.Builder.
• Example:
• import android.app.AlertDialog
• import android.content.Context