Welcome to our Kotlin Tutorial! Today, we'll delve into the structure of a typical Kotlin program. By the end of this lesson, you'll have a solid understanding of how to write, read, and run a Kotlin program. š”
Kotlin is a modern, statically-typed, and concise programming language that is fully interoperable with Java. It's a great choice for Android app development and is also used in other domains like server-side development and multiplatform projects.
Every Kotlin program starts with a fun main(args: Array<String>) function. This is the entry point of your program.
fun main(args: Array<String>) {
println("Hello, World!")
}š” Pro Tip: In Kotlin, every function is declared with the fun keyword and takes a list of parameters within parentheses.
Variables in Kotlin are declared using the var keyword for mutable variables and val for immutable ones. Kotlin has several basic data types, such as:
Int: Signed 32-bit integersFloat: Single-precision floating-point numbersBoolean: True or false valuesString: Sequence of charactersvar myInt: Int = 42
val myFloat: Float = 3.14f
val myBoolean: Boolean = true
val myString: String = "Kotlin is fun!"š” Pro Tip: In Kotlin, you need to explicitly declare the type of a variable.
Control structures like if, else, when, and loops (for, while, do-while) allow you to make decisions and iterate through data in your programs.
val number = 10
if (number > 5) {
println("The number is greater than 5")
} else {
println("The number is less than or equal to 5")
}The when statement is a more concise alternative to the if-else statement for handling multiple conditions.
val number = 10
when (number) {
1 -> println("Number is 1")
10 -> println("Number is 10")
else -> println("Number is not 1 or 10")
}Functions in Kotlin help break down complex tasks into smaller, manageable units. They are declared using the fun keyword, as we've seen before.
fun greet(name: String) {
println("Hello, $name!")
}
greet("World") // Output: Hello, World!š” Pro Tip: You can pass arguments to functions, just like we did with the greet function.
What is the entry point of every Kotlin program?
That's it for today's Kotlin Program Structure lesson! In the next lesson, we'll delve deeper into functions, exploring higher-order functions, lambdas, and extensions. Stay tuned! š
Happy coding! šš