Kotlin syntax forms the foundation of writing clean, concise, and effective code in the Kotlin programming language. Understanding these fundamental rules is crucial for developers looking to harness the power of Kotlin.
Kotlin programs typically start with a main()
function, which serves as the entry point. Unlike Java, Kotlin doesn't require semicolons at the end of statements.
fun main() {
println("Hello, Kotlin!")
}
Kotlin uses type inference, allowing you to declare variables without explicitly stating their type. Use val
for read-only variables and var
for mutable ones.
val readOnly = 42
var mutable = "Can be changed"
mutable = "New value"
For more details on variables, check out the guide on Kotlin Variables.
Functions in Kotlin are declared using the fun
keyword. They can have parameters and return values.
fun greet(name: String): String {
return "Hello, $name!"
}
val greeting = greet("Kotlin")
println(greeting) // Outputs: Hello, Kotlin!
Explore more about functions in the Kotlin Function Basics guide.
Kotlin provides familiar control flow structures with some enhancements:
val max = if (a > b) a else b
when (x) {
1 -> print("x is 1")
2 -> print("x is 2")
else -> print("x is neither 1 nor 2")
}
For more on control flow, see Kotlin If-Else Statements and Kotlin When Expression.
Kotlin supports various types of loops:
for (item in collection) {
println(item)
}
while (condition) {
// code to be repeated
}
Learn more about loops in Kotlin For Loops and Kotlin While Loops.
Kotlin simplifies class declarations:
class Person(val name: String, var age: Int)
val person = Person("Alice", 30)
println("${person.name} is ${person.age} years old")
Dive deeper into object-oriented programming in Kotlin with the Kotlin Classes guide.
Kotlin emphasizes null safety. By default, variables cannot hold null values unless explicitly declared as nullable:
var nonNull: String = "Hello"
// nonNull = null // This would cause a compilation error
var nullable: String? = "Hello"
nullable = null // This is allowed
Explore more about null safety in the Kotlin Nullable Types guide.
val
by default and only use var
when necessary.By mastering Kotlin syntax, you'll be well-equipped to write efficient, safe, and expressive code. As you progress, explore more advanced topics like Kotlin Coroutine Basics and Kotlin Extension Functions Basics to unlock the full potential of the language.