Kotlin Data Types
Kotlin has a rich set of built-in data types, including:
Numbers: Kotlin supports several numeric types, including
Byte
,Short
,Int
,Long
,Float
, andDouble
. These types are used to represent integers, floating-point numbers, and other numeric values.Characters: Kotlin has a
Char
type that represents a single Unicode character.Booleans: Kotlin has a
Boolean
type that represents a value that is eithertrue
orfalse
.Strings: Kotlin has a
String
type that represents a sequence of characters.Arrays: Kotlin has an
Array
type that represents a fixed-size collection of elements of the same type.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"}") }Sourcwww: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.