Kotlin Data Types

Kotlin has a rich set of built-in data types, including:

  1. Numbers: Kotlin supports several numeric types, including Byte, Short, Int, Long, Float, and Double. These types are used to represent integers, floating-point numbers, and other numeric values.

  2. Characters: Kotlin has a Char type that represents a single Unicode character.

  3. Booleans: Kotlin has a Boolean type that represents a value that is either true or false.

  4. Strings: Kotlin has a String type that represents a sequence of characters.

  5. Arrays: Kotlin has an Array type that represents a fixed-size collection of elements of the same type.

  6. Nullability: Kotlin has a special notation for indicating whether a variable can be null or not. To make a variable nullable, you can add a ? to its type declaration (e.g., String?).

Here's an example that demonstrates the use of some of these data types:

fun main() {
    val age: Int = 30
    val height: Double = 1.75
    val name: String = "John Doe"
    val isActive: Boolean = true
    val favoriteColors: Array<String> = arrayOf("blue", "green", "red")
    val middleInitial: Char? = null

    println("Name: $name")
    println("Age: $age")
    println("Height: $height")
    println("Active: $isActive")
    println("Favorite Colors: ${favoriteColors.joinToString()}")
    println("Middle Initial: ${middleInitial ?: "N/A"}")
}
Sourc‮www:e‬.theitroad.com

In this program, we declare variables of different data types and initialize them with values. We then use string interpolation to print the values of these variables to the console. Note that the middleInitial variable is declared as nullable using the ? notation, and we use the elvis operator (?:) to provide a default value if it is null. Finally, we use the joinToString() function to convert the favoriteColors array to a comma-separated string for printing.