Mastering Android Development with Kotlin
Kotlin Basics
Your First Kotlin Program
Every programming journey starts with a single line of code. In Kotlin, the entry point for any program is a special function called main. This is where your program begins its execution. To print something to the screen, we use the println() function. Let's combine them.
// This is the main function. Every Kotlin program needs one.
fun main() {
// println() prints text to the console, then adds a new line.
println("Hello, Kotlin!")
}
Here, fun is the keyword used to declare a function. The name of our function is main. The code inside the curly braces {} is what the function does. Simple, right? You don't need to worry about semicolons at the end of lines; Kotlin doesn't require them.
Storing Information
Programs need to remember things. We store information in variables. In Kotlin, there are two main ways to declare a variable:
val: This is for a value that won't change. Once you assign something to aval, it's final. Think of it as a constant.var: This is for a variable whose value can change later on.
It's a good practice to use val whenever possible. This makes your code safer and easier to understand, as it prevents accidental changes to data.
// Using val for a value that doesn't change.
val name: String = "Alex"
// Using var for a value that might change.
var score: Int = 0
score = 10 // This is okay, because score is a var.
Notice the : String and : Int. These are type declarations. They tell Kotlin what kind of data the variable will hold. Some basic types you'll use all the time are:
String: For text, like"Hello".Int: For whole numbers, like10or-5.Double: For decimal numbers, like3.14.Boolean: For true or false values.
Kotlin is smart. Often, you don't even need to write the type. The compiler can figure it out from the value you assign. This is called type inference.
// Kotlin infers that language is a String.
val language = "Kotlin"
// Kotlin infers that year is an Int.
val year = 2024
Controlling the Flow
Programs rarely run straight from top to bottom. They need to make decisions and repeat actions. This is called control flow.
To make a decision, we can use an
if-elsestatement. It checks if a condition is true and runs a block of code accordingly.
val temperature = 25
if (temperature > 20) {
println("It's a warm day.")
} else {
println("It's a bit chilly.")
}
For more complex choices, Kotlin gives us the when expression. It's like a more powerful version of the switch statement found in other languages.
val httpStatusCode = 404
val message = when (httpStatusCode) {
200 -> "OK"
404 -> "Not Found"
500 -> "Server Error"
else -> "Unknown Code"
}
println(message) // Prints "Not Found"
What if you need to do something over and over? That's what loops are for. A for loop is great for running a block of code a specific number of times or for iterating over items in a collection.
// This loop will print numbers from 1 to 3
for (i in 1..3) {
println("Launch sequence: $i")
}
The while loop is a bit different. It keeps running as long as its condition remains true. Be careful not to create an infinite loop!
var countdown = 3
while (countdown > 0) {
println(countdown)
countdown = countdown - 1 // or countdown--
}
println("Liftoff!")
Functions and Classes
As programs grow, you'll want to organize your code into reusable pieces. Functions are the first step. A function is a named block of code that performs a specific task. We've already seen the main function.
Here’s how you write your own. This function takes two integers as input and returns their sum.
// Defines a function named 'add'
// It takes two parameters, a and b, both of type Int
// It returns a value of type Int
fun add(a: Int, b: Int): Int {
return a + b
}
// You can then call the function like this:
val sum = add(5, 3) // sum is now 8
For even more organization, we use classes. A class is a blueprint for creating objects. Think of Car as a class. It defines the properties (like color and brand) and functions (like startEngine()) that all cars have. An object is a specific instance of that class, like your red Toyota or my blue Ford.
Here’s a simple Dog class.
class Dog(val name: String, val breed: String) {
// A function inside a class is called a method
fun bark() {
println("$name says: Woof!")
}
}
fun main() {
// Create an object (instance) of the Dog class
val myDog = Dog("Buddy", "Golden Retriever")
// Access its property
println("My dog's name is ${myDog.name}")
// Call its method
myDog.bark()
}
We can also create classes that build upon other classes. This is called inheritance. Imagine a Poodle class that inherits from Dog. It gets all the properties and methods of Dog but can also add its own, like doFancyTrick().
// 'open' allows other classes to inherit from Dog
open class Dog(val name: String) {
open fun bark() {
println("Woof!")
}
}
// Poodle inherits from Dog
class Poodle(name: String) : Dog(name) {
// 'override' modifies the inherited function
override fun bark() {
println("Yip!")
}
}
These are the fundamental building blocks of Kotlin. With variables, control flow, functions, and classes, you have the tools to start building your own programs.