Kotlin Syntax

Kotlin Tutorial

 Kotlin Syntax – Complete Beginner Guide

Kotlin is a modern, concise, and safe programming language mainly used for Android development, but also for backend, web, and desktop apps.


 1. Hello World Program

  • fun → function keyword
  • main() → entry point
  • println() → prints output

2. Variables in Kotlin

val (Immutable – cannot change)

var (Mutable – can change)

  •  Kotlin encourages val over var

3. Data Types

Kotlin is statically typed, but supports type inference.

Common Types

  • Int

  • Long

  • Float

  • Double

  • Boolean

  • String

  • Char


 4. Type Inference

Compiler automatically detects type:

  •  Cleaner syntax
  •  Less boilerplate

 5. Comments

Single-line

Multi-line


 6. String Templates (Very Important)


 

  •  No need for + concatenation

 7. Conditional Statements

 if – else


 

 if as Expression

  •  Kotlin treats if as an expression

 8. When Statement (switch replacement)


 

  •  More powerful than switch

 9. Loops

 for loop

 while loop

 do-while loop


10. Functions

Short Function (Single Expression)

  •  Clean and concise

11. Null Safety (Kotlin’s Superpower)

Nullable Variable

Safe Call

Elvis Operator

 NullPointerException avoided!


12. Arrays & Collections

Array

List

Map


 13. Class & Object


 

  •  Constructor built-in
  •  Less boilerplate than Java

14. Data Class

 Auto generates:

  • toString()

  • equals()

  • hashCode()

  • copy()


15. Companion Object (Static Alternative)

Call:


 Common Kotlin Syntax Mistakes

  • Using var everywhere

  • Ignoring null safety

  • Forgetting else in when

  • Using Java-style code


 Best Practices

  •  Prefer val
  •  Use expression syntax
  •  Handle nulls properly
  •  Keep functions small
  •  Write idiomatic Kotlin

 Interview Quick Questions

Q1. Is Kotlin statically typed?
Yes.

Q2. Difference between val and var?
val = read-only, var = mutable

Q3. Kotlin alternative to switch?
when

Q4. Can Kotlin run on JVM?
Yes.


 Summary

  •  Simple & expressive syntax
  •  Less boilerplate than Java
  •  Built-in null safety
  •  Perfect for Android & backend

You may also like...