Kotlin Basic Syntax Tutorial: main Function, Variables, Data Types, and Null Safety
This Kotlin Basic Syntax tutorial explains the core building blocks of Kotlin programming, including the main function, variables using val and var, data types, type inference, comments, string templates, and nullable versus non-nullable types. The chapter provides clear explanations, coding best practices, and practical examples to help beginners write clean, safe, and readable Kotlin programs.
Kotlin Basic Syntax – Complete Tutorial
main Function
The main function is the entry point of a Kotlin program. Execution always starts from this function.
Example
Best Practices
- Keep the
mainfunction minimal. - Move business logic into separate functions.
Variables: val and var
Kotlin provides two ways to declare variables.
val (Immutable Variable)
- Value cannot be changed after assignment.
- Similar to
finalin Java.
var (Mutable Variable)
- Value can be changed.
Best Practices
- Prefer
valby default. - Use
varonly when mutation is required.
Data Types
Kotlin is a statically typed language, but it handles types intelligently.
Common Data Types
- Int
- Long
- Double
- Float
- Boolean
- Char
- String
Example
Best Practices
- Use explicit types for clarity in complex logic.
- Avoid unnecessary type casting.
Type Inference
Kotlin automatically infers the data type based on the assigned value.
Example
Best Practices
- Rely on type inference for simple declarations.
- Declare types explicitly in public APIs.
Comments
Comments are used to explain code and improve readability.
Single-Line Comment
Multi-Line Comment
Best Practices
- Write comments to explain why, not what.
- Keep comments updated with code changes.
String Templates
String templates allow embedding variables and expressions directly inside strings.
Example
Expression Example
Best Practices
- Use string templates instead of string concatenation.
- Keep expressions simple inside templates.
Nullable and Non-Nullable Types
Kotlin distinguishes between nullable and non-nullable types to avoid NullPointerException.
Non-Nullable Type
Nullable Type
Safe Call Operator
Elvis Operator
Non-Null Assertion (Use with caution)
Best Practices
- Avoid
!!whenever possible. - Use safe calls and Elvis operator for safer code.
Summary
In this chapter, you learned Kotlin’s basic syntax, including the main function, variable declarations, data types, type inference, comments, string templates, and null safety. Mastering these concepts is essential for writing clean, safe, and maintainable Kotlin code.