Basic syntax
var name: String = "John Doe"
Functions
Functions are blocks of code that perform specific tasks. They are defined using the fun keyword followed by the function name and parentheses containing the function parameters. The function body is enclosed in curly braces. For example, to define a function named greet that takes a name parameter and prints a greeting message, you would write:
fun greet(name: String) {
println("Hello, $name!")
}
Classes and objects
Classes are blueprints for creating objects. They are defined using the class keyword followed by the class name and curly braces containing the class members (properties and methods). Objects are instances of classes and are created using the new operator followed by the class name and parentheses containing the constructor arguments. For example, to define a class named Person with properties name and age and a method introduce(), you would write:
class Person(var name: String, var age: Int) {
fun introduce() {
println("Hello, my name is $name and I am $age years old.")
}
}
Nullability
Kotlin has a powerful nullability system that helps prevent null pointer exceptions. A variable or expression can be declared as nullable using the ? operator. For example, to declare a variable named message that can be null, you would write:
var message: String? = null
Additional features
Kotlin has many other features that make it a powerful and versatile programming language, including:
This is just a brief overview of Kotlin syntax. There are many more features and concepts to explore, but this should give you a good starting point for learning the language.