Python Logo

Kotlin Syntax


Basic syntax

  • Variables: Variables are declared using the var keyword followed by the variable name and type. For example, to declare a variable named name of type String, you would write:

var name: String = "John Doe"

  • Data types: Kotlin has a variety of data types, including primitive types like Int, Double, and Boolean, as well as object types like String and List.
  • Operators: Kotlin supports a wide range of operators, including arithmetic operators, comparison operators, logical operators, and assignment operators.
  • Control flow statements: Kotlin provides control flow statements for conditional branching and looping, such as if, else, for, while, and when.

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:

  • Type inference: Kotlin infers the type of variables from their values, which can make code more concise.
  • Extension functions: Extension functions allow you to add new functionality to existing classes without modifying the original class definition.
  • Higher-order functions: Higher-order functions are functions that take other functions as arguments or return functions as results.
  • Data classes: Data classes are a special type of class that is designed to hold data. They have automatically generated properties and methods for common data operations.

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.