Kotlin Program Structure šŸš€

beginner
14 min

Kotlin Program Structure šŸš€

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. šŸ’”

What is Kotlin? šŸŽÆ

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.

Basic Program Structure šŸ“

Every Kotlin program starts with a fun main(args: Array<String>) function. This is the entry point of your program.

kotlin
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 and Types šŸ“

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 integers
  • Float: Single-precision floating-point numbers
  • Boolean: True or false values
  • String: Sequence of characters
kotlin
var 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 šŸ“

Control structures like if, else, when, and loops (for, while, do-while) allow you to make decisions and iterate through data in your programs.

If and Else Statements šŸ“

kotlin
val number = 10 if (number > 5) { println("The number is greater than 5") } else { println("The number is less than or equal to 5") }

When Statement šŸ“

The when statement is a more concise alternative to the if-else statement for handling multiple conditions.

kotlin
val number = 10 when (number) { 1 -> println("Number is 1") 10 -> println("Number is 10") else -> println("Number is not 1 or 10") }

Functions šŸ“

Functions in Kotlin help break down complex tasks into smaller, manageable units. They are declared using the fun keyword, as we've seen before.

kotlin
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.

Quiz šŸŽÆ

Quick Quiz
Question 1 of 1

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! šŸš€šŸŽ‰