Kotlin has a rich type system and is statically typed. Basic types include:
Int, Long, Short, ByteFloat, DoubleChar, Boolean, Stringval count: Int = 42
val pi: Double = 3.14
val grade: Char = 'A'
val isPassed: Boolean = true
val name: String = "Kotlin"Kotlin automatically infers types when possible:
val score = 99 // Int
val version = 1.8 // Double
val language = "Kotlin" // StringUse explicit typing when needed for clarity or external APIs.
Kotlin’s type system distinguishes between nullable and non-null types. Use ? to declare a variable that can hold null.
var city: String? = "Toronto"
city = null // OK
var country: String = "Canada"
country = null // ❌ Compile-time errorKotlin provides several powerful operators to handle null values safely and concisely. These include the safe call operator ?., the Elvis operator ?:, and the non-null assertion operator !!.
?. — Safe Call: Accesses a property or method only if the variable is not null. If it is null, the whole expression evaluates to null (instead of throwing an exception).?: — Elvis Operator: Provides a default value if the expression on the left is null.!! — Non-null Assertion: Forces the variable to be treated as non-null. Will throw a NullPointerException if the variable is actually null.Example:
val city: String? = null
println(city?.length) // Safe call: prints null instead of crashing
println(city ?: "Unknown") // Elvis operator: prints "Unknown"
println(city!!.length) // ❌ Throws NullPointerException (do not use unless you're 100% sure city is not null)Kotlin does not allow implicit conversions between number types:
val a: Int = 10
val b: Long = a.toLong()
val f: Float = b.toFloat()Use toInt(), toDouble(), etc. for explicit conversions.
Kotlin supports string interpolation using $ syntax:
Ask the AI if you need help understanding or want to dive deeper in any topic