Basic Syntax
Overview
This chapter provides detailed coverage of Kotlin's basic syntax rules, including identifiers, keywords, comments, package declarations, import statements, and other fundamental concepts. Mastering these syntax rules is essential for writing correct Kotlin code.
Identifiers and Naming Rules
Identifier Rules
Naming Conventions
Keywords
Hard Keywords (Cannot Be Used as Identifiers)
Soft Keywords (Have Special Meaning in Specific Contexts)
Comments
Single-Line Comments
Multi-Line Comments
Documentation Comments (KDoc)
Package Declaration and Imports
Package Declaration
Import Statements
Default Imports
Statements and Expressions
Statements vs Expressions
Block Expressions
Semicolons
Literals
Numeric Literals
Character Literals
String Literals
Boolean Literals
Operator Precedence
Type System Basics
Basic Types
Nullable Types
Scope and Visibility
Local Scope
Function Scope
Coding Conventions
Indentation and Formatting
Naming Convention Summary
Common Syntax Errors
1. Semicolon Usage Errors
2. Nullability Errors
3. Type Inference Errors
Best Practices
- Follow Kotlin coding conventions
- Use meaningful variable and function names
- Use comments appropriately, especially KDoc
- Keep code concise and readable
- Leverage type inference but specify types when necessary
Next Steps
After mastering the basic syntax, let's learn about Kotlin's program structure, including classes, objects, packages, and other ways to organize code.
Next Chapter: Program Structure
Exercises
- Write a program demonstrating the use of all basic data types
- Create a function with complete KDoc documentation
- Practice different types of string literals and templates
- Write code demonstrating the effects of operator precedence
- Create a program to demonstrate scope rules