Basic Concepts in Kotlin

 Kotlin is a modern, statically-typed programming language that is fully interoperable with Java and widely used for Android development, server-side applications, and more. Below are some of the basic concepts in Kotlin:

 1. **Variables**

   - **`val`**: Immutable variable (read-only, cannot be reassigned).

     ```kotlin

     val name = "Kotlin"

     // name = "Java" // Error: val cannot be reassigned

     ```

   - **`var`**: Mutable variable (can be reassigned).

     ```kotlin

     var age = 25

     age = 26 // Valid

     ```

 2. **Data Types**

   Kotlin is statically typed, but it supports type inference. Common data types include:

   - **Numbers**: `Int`, `Long`, `Double`, `Float`, etc.

   - **Booleans**: `true`, `false`

   - **Characters**: `Char`

   - **Strings**: `String`

   - **Arrays**: `Array<T>`

   - **Collections**: `List`, `Set`, `Map`


   Example:

   ```kotlin

   val number: Int = 10

   val pi: Double = 3.14

   val isKotlinFun: Boolean = true

   val letter: Char = 'A'

   val text: String = "Hello, Kotlin!"

   ```

3. **Functions**

   Functions are declared using the `fun` keyword.

   ```kotlin

   fun greet(name: String): String {

       return "Hello, $name!"

   }

   ```

   - Single-expression functions can be shortened:

     ```kotlin

     fun greet(name: String) = "Hello, $name!"

      4. **Control Flow**

   - **`if` Expression**:

     In Kotlin, `if` can be used as an expression (returns a value).

     ```kotlin

     val max = if (a > b) a else b

     ```

   - **`when` Expression**:

     Similar to `switch` in other languages but more powerful.

     ```kotlin

     when (x) {

         1 -> print("x is 1")

         2 -> print("x is 2")

         else -> print("x is neither 1 nor 2")

     }

     ```

   - **Loops**:

     - `for` loop:

       ```kotlin

       for (i in 1..5) {

           println(i)

       }

       ```

     - `while` and `do-while` loops:

       ```kotlin

       while (condition) {

           // Code

       }

    

5. **Null Safety**

   Kotlin eliminates null pointer exceptions by distinguishing between nullable and non-nullable types.

   - Use `?` to declare a nullable type:

     ```kotlin

     var name: String? = null

     ```

   - Safe call operator (`?.`):

     ```kotlin

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

     ```

   - Elvis operator (`?:`):

     ```kotlin

     val length = name?.length ?: 0 // Returns 0 if name is null

     ```


6. **Classes and Objects**

   - **Class Declaration**:

     ```kotlin

     class Person(val name: String, var age: Int)

     ```

   - **Object Declaration** (Singleton):

     ```kotlin

     object Database {

         fun connect() { /* ... */ }

     }

    

 7. **Data Classes**

   Data classes are used to hold data and automatically generate `toString()`, `equals()`, `hashCode()`, and `copy()` methods.

   ```kotlin

   data class User(val name: String, val age: Int)

   

 8. **Collections**

   Kotlin provides both mutable and immutable collections:

   - Immutable: `List`, `Set`, `Map`

   - Mutable: `MutableList`, `MutableSet`, `MutableMap`

   Example:

   ```kotlin

   val numbers = listOf(1, 2, 3)

   val mutableNumbers = mutableListOf(1, 2, 3)

   ```


9. **Lambdas and Higher-Order Functions**

   - **Lambda**:

     ```kotlin

     val sum = { a: Int, b: Int -> a + b }

     println(sum(2, 3)) // Output: 5

     ```

   - **Higher-Order Function**:

     A function that takes another function as a parameter or returns a function.

     ```kotlin

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

         return operation(a, b)

     }

     ```

10. **Extensions**

   Kotlin allows adding new functionality to existing classes without modifying their source code.

   ```kotlin

   fun String.isPalindrome(): Boolean {

       return this == this.reversed()

   }

   println("racecar".isPalindrome()) // Output: true

   ```

 11. **Coroutines**

   Kotlin provides built-in support for asynchronous programming using coroutines.

   ```kotlin

   import kotlinx.coroutines.*


   fun main() = runBlocking {

       launch {

           delay(1000L)

           println("World!")

       }

       println("Hello,")

   }

   ```

### 12. **Interoperability with Java**

   Kotlin is fully interoperable with Java, meaning you can call Java code from Kotlin and vice versa.



Comments

Popular posts from this blog

Kotlin Math Operations and Functions Overview

Kotlin Strings: Features and Operations Guide

Kotlin Android Program (QCR) Application Codes That Read Text in Photos