Kotlin Basic Syntax Tutorial
Kotlin is a modern programming language that runs on the Java Virtual Machine (JVM) and can also be compiled to JavaScript or native code. It’s known for its concise syntax, interoperability with Java, and strong type inference. In this tutorial, we’ll cover the basic syntax of Kotlin with code examples to help you get started.
1. Variables and Data Types
In Kotlin, variable declaration follows the pattern val
or var
followed by the name of the variable and its type (optional if it can be inferred).
// Immutable variable (read-only)
val name: String = "John"
// Mutable variable
var age: Int = 30
Kotlin provides a rich set of data types, including Int
, Long
, Double
, Float
, Boolean
, Char
, String
, and more.
2. Functions
Functions in Kotlin are declared using the fun
keyword. They can take parameters and return values.
fun add(a: Int, b: Int): Int {
return a + b
}
// Function with inferred return type
fun multiply(a: Int, b: Int) = a * b
3. Control Flow
Kotlin supports standard control flow structures like if
, else
, for
, while
, and when
.
val x = 10
val y = 5
if (x > y) {
println("x is greater than y")
} else {
println("y is greater than or equal to x")
}
for (i in 1..5) {
println(i)
}
when (x) {
1 -> println("x is 1")
2 -> println("x is 2")
else -> println("x is neither 1 nor 2")
}
4. Nullable Types
In Kotlin, types cannot have a value of null
by default. If you need a variable to be nullable, you can declare its type followed by a question mark ?
.
var nullableString: String? = null
5. String Templates
Kotlin supports string templates, allowing you to embed expressions directly in strings.
val name = "Alice"
val greeting = "Hello, $name!"
println(greeting) // Output: Hello, Alice!
Conclusion
This tutorial covered the basic syntax of Kotlin, including variables, data types, functions, control flow, nullable types, and string templates. With this foundation, you’re well-equipped to start writing Kotlin code. Experiment with these concepts and explore more advanced features to become proficient in Kotlin programming.