Kotlin Introduction
Understanding Kotlin programming language fundamentals
🎯 What is Kotlin?
Kotlin is a statically typed programming language developed by JetBrains. It's designed to be fully interoperable with Java while providing modern language features and concise syntax for better productivity.
// Simple Kotlin program
fun main() {
val message = "Welcome to Kotlin!"
println(message)
}
Output:
Key Kotlin Features
Null Safety
Eliminates null pointer exceptions
var name: String? = null
println(name?.length)
Data Classes
Automatic generation of common methods
data class User(val name: String, val age: Int)
Extension Functions
Add functionality to existing classes
fun String.isEmail() = contains("@")
Smart Casts
Automatic type casting after checks
if (obj is String) {
println(obj.length) // Smart cast
}
🔹 Kotlin vs Java
See how Kotlin simplifies common programming tasks:
🔸 Creating a Simple Class
Java:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
}
Kotlin:
data class Person(val name: String, val age: Int)
🔹 Basic Kotlin Syntax
Understanding Kotlin's fundamental syntax elements:
// Variables
val immutable = "Cannot change" // Read-only
var mutable = "Can change" // Mutable
// Functions
fun add(a: Int, b: Int): Int {
return a + b
}
// Simplified function
fun multiply(a: Int, b: Int) = a * b
// String templates
val name = "Kotlin"
println("Hello, $name!")
println("Length: ${name.length}")
Output:
Length: 6
🔹 Where Kotlin is Used
Popular Applications:
- Android Development: Native Android apps
- Server-side Development: Web applications and APIs
- Desktop Applications: Cross-platform desktop apps
- Web Development: Frontend with Kotlin/JS
- Data Science: Data analysis and machine learning
🔹 Your First Kotlin Program
Let's create a simple program that demonstrates basic Kotlin concepts:
fun main() {
// Variables
val language = "Kotlin"
var version = 1.8
// Function call
printInfo(language, version)
// Conditional
if (version >= 1.5) {
println("Modern Kotlin version!")
}
}
fun printInfo(lang: String, ver: Double) {
println("Language: $lang")
println("Version: $ver")
}
Output:
Version: 1.8
Modern Kotlin version!