Welcome to the world of Kotlin programming! In this blog, we will cover some basic syntax elements in Kotlin.
Variables:
Variables in Kotlin can be declared using the var
keyword for mutable variables and the val
keyword for immutable variables. For example:
var x = 5 // mutable variable
val y = 10 // immutable variable
You can also specify the data type of a variable using the :
operator. For example:
var x: Int = 5
val y: Double = 3.14
Creating classes:
In Kotlin, you can create classes using the class
keyword. For example:
class MyClass {
val x: Int = 10
fun printX() {
println(x)
}
}
You can create an instance of a class using the new
keyword or by calling the class name as a function. For example:
val obj1 = MyClass()
val obj2 = MyClass
Comments:
In Kotlin, you can use single-line comments by starting a line with //
. For example:
// This is a single-line comment
You can also use multi-line comments by enclosing them in /*
and */
. For example:
/*
This is a
multi-line
comment
*/
String:
In Kotlin, a string is a sequence of characters represented by the String
data type. You can create a string using double quotes ("
) or triple quotes ("""
). For example:
val str1 = "Hello, Kotlin"
val str2 = """Hello,
Kotlin"""
Triple quotes are useful for creating multi-line strings. They preserve the line breaks and whitespace in the string.
Conditional expressions
fun main() {
val x = 10
if (x > 5) {
println("x is greater than 5")
} else {
println("x is less than or equal to 5")
}
}
while loop:
while (count < 5) {
println(count)
count++
}
when:
val x = 3
when (x) {
1 -> println("x is 1")
2 -> println("x is 2")
3 -> println("x is 3")
else -> println("x is something else")
}
Ranges:
val x = 3
val y = 10
// Check if x is in the range 1 to 10 (inclusive)
if (x in 1..10) {
println("x is between 1 and 10")
}
// Check if y is outside the range 1 to 10 (exclusive)
if (y !in 1 until 10) {
println("y is not between 1 and 10")
}
Collections:
val numbers = listOf(1, 2, 3, 4, 5)
val firstItem = numbers[0] // firstItem is 1
val lastItem = numbers[numbers.size - 1] // lastItem is 5
for (number in numbers) {
println(number)
}
Nullable:
In Kotlin, a nullable type is a type that can hold either a value or null
. You can declare a nullable type by adding a ?
after the type name. For example:
val s: String? = null
val length = s?.length // length is null
val x = "hello"
if (x is String) {
println("x is a string")
}