Kotlin Tutorial

Master the modern language Google recommends for Android, backend, and multiplatform apps

Null Safe Concise Android Coroutines

Table of Contents

1What is Kotlin?

Kotlin is a modern, statically typed programming language developed by JetBrains. It runs on the Java Virtual Machine (JVM), Android, browsers (Kotlin/JS), and native platforms (Kotlin/Native). Google officially supports Kotlin as the preferred language for Android app development.

Kotlin was designed to be 100% interoperable with Java — you can call Java from Kotlin and vice versa in the same project. This made adoption easy for millions of existing Android and enterprise Java codebases. Kotlin code is typically more concise, safer (null safety built in), and expressive than equivalent Java.

Key Idea

Kotlin is not just an Android language — it's used for server-side (Spring, Ktor), multiplatform mobile (KMP), and data science tooling.

2Features of Kotlin

Kotlin's popularity comes from language features that reduce boilerplate and common bugs:

Null Safety

Nullable types (String?) enforced at compile time — fewer NullPointerExceptions.

Concise Syntax

Data classes, type inference, and smart casts cut verbose Java boilerplate dramatically.

Java Interop

Use existing Java libraries and gradually migrate files — no big-bang rewrite required.

Coroutines

First-class async programming with structured concurrency for Android and server apps.

Data Classes

data class User(val id: Int, val name: String) auto-generates equals, hashCode, copy.

Extension Functions

Add functions to existing classes without inheritance — great for UI helpers.

Sealed Classes

Restricted class hierarchies for exhaustive when expressions — ideal for UI state.

Multiplatform

Kotlin Multiplatform shares business logic across Android, iOS, desktop, and web.

3History & Versions

Kotlin was unveiled by JetBrains in 2011 and reached 1.0 in 2016. Google announced Kotlin as an official Android language at Google I/O 2017, with Android Studio receiving first-class Kotlin support.

YearMilestoneSignificance
2011JetBrains announces KotlinOpen-source language project begins
2016Kotlin 1.0Production-ready release
2017Google I/O — Android supportOfficial Android language alongside Java
2019Google: Kotlin preferredNew Android projects default to Kotlin
2020+Kotlin 1.4 – 2.xKMP stable, coroutines, K2 compiler, Compose
Note: Kotlin releases frequently with language improvements. Check kotlinlang.org releases for the latest stable version.

4Kotlin vs Java

Both languages compile to JVM bytecode and work on Android. Kotlin is designed as a modern alternative while preserving Java ecosystem access.

AspectKotlinJava
Null safetyBuilt into type system (?)Optional annotations; NPE at runtime
BoilerplateData classes, properties, whenGetters/setters, verbose POJOs
FunctionsTop-level functions, extensionsMust live inside classes (pre-Java 21)
AsyncCoroutines (suspend functions)Threads, CompletableFuture, RxJava
Android defaultGoogle recommended since 2019Legacy codebases still common
InteropCalls Java seamlesslyCalls Kotlin (mind nullable types)
Kotlin vs Java — same logic// Java (verbose) // public class Greeter { // private final String name; // public Greeter(String name) { this.name = name; } // public String greet() { return "Hello, " + name; } // } // Kotlin (concise) data class Greeter(val name: String) { fun greet() = "Hello, $name" }

5Where Kotlin is Used

Android Apps

Google apps, most new Play Store apps, Jetpack Compose UI, Room, ViewModel.

Backend Services

Spring Boot, Ktor, Micronaut — REST APIs and microservices on JVM.

Kotlin Multiplatform

Share networking, models, and business logic between Android and iOS.

Desktop (Compose)

Compose Multiplatform for cross-platform desktop UIs with shared Kotlin code.

Data & Scripting

Kotlin notebooks, Gradle build scripts (.gradle.kts), automation.

Enterprise

Netflix, Pinterest, Uber, and many banks use Kotlin in production systems.

6Kotlin Platforms

Kotlin is multiplatform by design — the same language targets different runtimes:

Kotlin Source Code (.kt) │ ├── JVM (Android, Spring, server) → .class bytecode ├── Kotlin/JS (browser, Node.js) → JavaScript ├── Kotlin/Native (iOS, embedded) → native binaries └── Kotlin Multiplatform (KMP) → shared + platform-specific
JVM Kotlin on JVM

Default target. Compiles to bytecode compatible with Java. Used for Android and backend.

Tools: JDK, Gradle, Maven, Android Gradle Plugin.

JS Kotlin/JS

Web target. Compiles to JavaScript for browsers or Node.js applications.

Use case: Full-stack Kotlin with shared models.

N Kotlin/Native

Native binaries. No JVM required — useful for iOS, IoT, and performance-critical code.

Interop: C/Objective-C via cinterop.

M Multiplatform (KMP)

Share logic. Common module for business rules; expect/actual for platform APIs.

UI: Compose Multiplatform or native UI per platform.

7Tooling & Ecosystem

JetBrains and the open-source community provide excellent tooling for Kotlin development:

ToolPurpose
IntelliJ IDEA / Android StudioOfficial IDE with Kotlin plugin, refactoring, debugger
Gradle (Kotlin DSL)Build system — build.gradle.kts is Kotlin
kotlincCommand-line Kotlin compiler
kotlinlang.orgOfficial docs, Koans (interactive exercises), API reference
Jetpack librariesAndroid KTX extensions, Compose, Room, Navigation
Ktor / SpringPopular frameworks for server-side Kotlin
Bash — Check Kotlin compiler versionkotlinc -version # Or via Gradle in an Android project ./gradlew -q kotlinVersion

8Hello World

Every Kotlin program needs an entry point. On JVM, use the main function:

Standalone Kotlin (JVM)

Kotlin — Main.ktfun main() { println("Hello, Kotlin!") } fun greet(name: String): String { return "Hello, $name!" }

Android Activity (Kotlin)

Kotlin — MainActivity.ktclass MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val message = greet("Android") Log.d("MainActivity", message) } private fun greet(name: String) = "Hello, $name from Kotlin!" }

Run from command line

Bashkotlinc Main.kt -include-runtime -d hello.jar java -jar hello.jar # Output: Hello, Kotlin!

9Summary Cheatsheet

TopicKey Takeaway
What is Kotlin?Modern JVM language by JetBrains; official for Android
Core FeaturesNull safety, conciseness, coroutines, data classes
vs JavaLess boilerplate; full Java interop; preferred for new Android
PlatformsJVM, JS, Native, Multiplatform
ToolingIntelliJ, Android Studio, Gradle KTS, kotlinlang.org
Entry pointfun main() for CLI; Activity for Android
Learning pathBasics → OOP → Collections → Coroutines → Android/Compose

10Next Steps for Learning

1

Complete Setup & Installation — install JDK, IntelliJ or Android Studio, and verify kotlinc.

2

Learn Kotlin Basics — variables, types, strings, and operators.

3

Master Null Safety — one of Kotlin's biggest advantages over Java.

4

Study OOP and Data Classes for real-world modeling.

5

Explore Coroutines for async Android and backend code.

6

Build apps with Android Development and Jetpack Compose.

Kotlin MCQ Practice

10 Basic MCQs 10 Advanced MCQs

10 Basic Kotlin MCQs

1

Who developed the Kotlin programming language?

AGoogle
BJetBrains
CMicrosoft
DOracle
Explanation: Kotlin was created by JetBrains, the company behind IntelliJ IDEA, and released as an open-source language in 2011.
2

What runtime does Kotlin primarily target for Android and backend development?

A.NET CLR
BJava Virtual Machine (JVM)
CNode.js V8 only
DPython interpreter
Explanation: Kotlin on JVM compiles to bytecode (.class files) compatible with Java, making it ideal for Android and server-side apps.
3

Which symbol marks a nullable type in Kotlin?

A!
B?
C*
D@
Explanation: Appending ? to a type (e.g., String?) tells the compiler the value may be null — a core null-safety feature.
4

What is the standard entry point for a standalone Kotlin JVM program?

Afun main()
Bpublic static void main
Cdef main():
Dvoid start()
Explanation: Kotlin uses fun main() as the program entry point on the JVM, replacing Java's verbose main method signature.
5

Which company officially supports Kotlin as the preferred language for Android?

AApple
BMeta
CGoogle
DAmazon
Explanation: Google announced Kotlin as an official Android language at Google I/O 2017 and made it the preferred choice for new projects in 2019.
6

Kotlin is designed to be 100% interoperable with which language?

APython
BJava
CSwift
DRust
Explanation: Kotlin and Java can coexist in the same project — you can call Java libraries from Kotlin and Kotlin from Java without rewriting everything.
7

Which Gradle build file format uses Kotlin syntax?

Abuild.gradle.kts
Bbuild.xml
Cpom.xml
Dpackage.json
Explanation: Gradle Kotlin DSL uses .gradle.kts files, letting you write type-safe build scripts in Kotlin instead of Groovy.
8

What does Kotlin compile to when targeting the JVM?

AMachine code directly
BJava bytecode (.class files)
CPython bytecode
DWebAssembly only
Explanation: The Kotlin JVM compiler (kotlinc) produces bytecode that runs on any JVM, same as Java.
9

Which IDE is most commonly used for Kotlin development?

AIntelliJ IDEA / Android Studio
BNotepad++
CDev-C++
DScratch IDE
Explanation: IntelliJ IDEA (by JetBrains) has first-class Kotlin support. Android Studio is built on IntelliJ and is the standard for Android Kotlin apps.
10

When did Kotlin reach its first production-ready release (1.0)?

A2005
B2011
C2016
D2020
Explanation: Kotlin was announced in 2011 and Kotlin 1.0 was released in February 2016, marking the language as production-ready.

10 Advanced Kotlin MCQs

1

What is Kotlin Multiplatform (KMP) primarily designed for?

ASharing business logic across Android, iOS, and other platforms
BReplacing the Linux kernel on Android
CCompiling Java to Swift automatically
DRunning Kotlin only in the browser
Explanation: KMP lets teams share networking, models, and business rules in a common module while using platform-specific UI (Compose or native).
2

What does Kotlin/Native compile to?

AJavaScript only
BNative binaries without requiring a JVM
CHTML templates
DSQL queries
Explanation: Kotlin/Native produces platform-native executables for iOS, embedded systems, and other targets where a JVM is not available.
3

What does a Kotlin data class automatically generate?

Aequals(), hashCode(), copy(), and toString()
BAndroid layout XML files
CDatabase migration scripts
DREST API endpoints
Explanation: Declaring data class User(val id: Int, val name: String) auto-generates boilerplate methods that would require dozens of lines in Java.
4

What are Kotlin coroutines primarily used for?

AAsynchronous and concurrent programming without blocking threads
BDefining XML layouts
CSigning APK files
DMemory garbage collection tuning
Explanation: Coroutines use suspend functions and structured concurrency for network calls, database I/O, and background work on Android and Ktor servers.
5

What is the main purpose of sealed classes in Kotlin?

ARestricted class hierarchies with exhaustive when expressions
BEncrypting class fields at runtime
CPreventing all inheritance
DConverting classes to interfaces
Explanation: Sealed classes model fixed sets of states (e.g., UI state, API results) and the compiler ensures all subclasses are handled in when.
6

What do extension functions allow you to do?

AAdd functions to existing classes without modifying their source or using inheritance
BExtend the JVM heap size
CReplace Java entirely in one step
DDisable null safety checks
Explanation: Extension functions like fun String.isEmail(): Boolean add utility methods to types you don't own — common in Android KTX libraries.
7

What does Kotlin/JS compile Kotlin source code into?

AJava bytecode
BJavaScript
CSwift source
DPython scripts
Explanation: Kotlin/JS targets browsers and Node.js by compiling to JavaScript, enabling full-stack Kotlin with shared models.
8

What does the Elvis operator (?:) do in Kotlin?

AReturns the right-hand value when the left side is null
BThrows NullPointerException immediately
CConverts Int to String
DDeclares a companion object
Explanation: Example: val name = user?.name ?: "Guest" — if user?.name is null, the default "Guest" is used.
9

In Kotlin Multiplatform, what are expect and actual declarations used for?

AUnit testing only
BGradle dependency resolution
CDeclaring common APIs in shared code with platform-specific implementations
DDefining Android Activities
Explanation: expect in common code declares an API; each platform provides an actual implementation (e.g., different file system APIs on Android vs iOS).
10

Which backend frameworks are commonly used with Kotlin on the JVM?

ASpring Boot and Ktor
BDjango and Flask only
CWordPress and Drupal
DUnity and Unreal Engine
Explanation: Spring Boot (enterprise REST/microservices) and Ktor (lightweight Kotlin-native server framework by JetBrains) are widely used for backend Kotlin.

15 Interview Questions & Answers

Easy Medium Hard
1What is Kotlin?easy
Answer: Kotlin is a modern, statically typed programming language developed by JetBrains. It runs on the JVM, Android, JavaScript (Kotlin/JS), and native platforms. Google officially supports it as the preferred language for Android development.
2Why is Kotlin preferred over Java for new Android projects?easy
Answer: Kotlin reduces boilerplate with data classes and type inference, has built-in null safety, supports coroutines for async work, is fully interoperable with Java, and is officially recommended by Google since 2019.
3What is null safety in Kotlin?easy
Answer: Kotlin distinguishes nullable (String?) and non-nullable (String) types at compile time. The compiler prevents assigning null to non-nullable types, reducing NullPointerExceptions significantly.
4What is the difference between val and var?easy
Answer: val declares an immutable reference (read-only — like Java final). var declares a mutable reference that can be reassigned. Both support type inference.
5What is a data class in Kotlin?easy
Answer: A data class is a class primarily for holding data. The compiler auto-generates equals(), hashCode(), toString(), copy(), and component functions from properties declared in the primary constructor.
6Explain Kotlin's interoperability with Java.medium
Answer: Kotlin and Java compile to the same JVM bytecode. You can mix .kt and .java files in one project, call Java libraries from Kotlin, and expose Kotlin code to Java (mind nullable types and default parameters via @JvmOverloads).
7What are coroutines and why use them?medium
Answer: Coroutines are lightweight concurrency primitives. suspend functions allow sequential-looking async code for network, database, and background tasks without blocking threads or nested callbacks.
8What is the difference between == and === in Kotlin?medium
Answer: == checks structural equality (calls equals()). === checks referential equality — whether two references point to the same object instance.
9What is a sealed class and when would you use one?medium
Answer: A sealed class restricts which classes can inherit from it (subclasses must be in the same file/module). Use sealed classes for fixed state hierarchies — API results, UI states — with exhaustive when branches checked at compile time.
10What are extension functions?medium
Answer: Extension functions add new functions to existing classes without modifying source code or using inheritance. Example: fun View.show() { visibility = View.VISIBLE } — widely used in Android KTX.
11What is Kotlin Multiplatform (KMP)?medium
Answer: KMP lets you share business logic (networking, models, validation) across Android, iOS, desktop, and web in a common module, using expect/actual for platform-specific APIs while keeping UI native or using Compose Multiplatform.
12Explain the safe call operator (?.) and Elvis operator (?:).medium
Answer: ?. safely accesses a member only if the receiver is non-null (returns null otherwise). ?: provides a default when the left expression is null: user?.email ?: "unknown@example.com".
13What is the difference between object, companion object, and class?hard
Answer: A class is instantiated with constructors. An object is a singleton — one instance created by the runtime. A companion object is a singleton inside a class, similar to Java static members but is a real object with its own name.
14How does Kotlin handle exceptions compared to Java?hard
Answer: Kotlin has no checked exceptions — you don't need try-catch for every IOException like in Java. Use try/catch/finally, throw, and custom exceptions similarly, but the compiler doesn't force handling of checked exceptions.
15Describe Kotlin's platform targets: JVM, JS, and Native.hard
Answer: JVM — default target; compiles to bytecode for Android and server (Spring, Ktor). Kotlin/JS — compiles to JavaScript for browsers/Node.js. Kotlin/Native — compiles to native binaries without JVM for iOS, embedded, and performance-critical code. KMP combines shared logic with platform-specific implementations.