Kotlin Syntax Fundamentals: Understanding the Basics

February 9, 2024

&lth2&gtVariables and Data Types&lt/h2&gt&ltp&gtIn Kotlin, you can declare a variable using the &ltcode&gtvar&lt/code&gt keyword for mutable variables or the &ltcode&gtval&lt/code&gt keyword for immutable variables. Here’s an example:&lt/pre&gt&ltcode&gtval pi: Double = 3.14&lt/code&gt&ltpre&gtThis declares an immutable variable &ltpre&gt&ltcode&gtpi&lt/code&gt&lt/pre&gt&ltpre&gt of type &ltpre&gt&ltcode&gtDouble&lt/code&gt&lt/pre&gt&ltpre&gt initialized with the value &ltpre&gt&ltcode&gt3.14&lt/code&gt&lt/pre&gt&ltpre&gt.&lt/pre&gt&lth2&gtControl Flow Structures&lt/h2&gt&ltp&gtKotlin supports the usual control flow structures such as &ltcode&gtif&lt/code&gt, &ltcode&gtwhen&lt/code&gt, &ltcode&gtfor&lt/code&gt, and &ltcode&gtwhile&lt/code&gt. Here’s an example of an &ltcode&gtif&lt/code&gt statement:&lt/pre&gt&ltcode&gtval number = 10
if (number &gt 0) {
println(“Positive number”)
} else if (number &lt 0) {
println(“Negative number”)
} else {
println(“Zero”)
}&lt/code&gt&ltpre&gtThis code snippet demonstrates an &ltcode&gtif&lt/code&gt statement that checks whether the variable &ltpre&gt&ltcode&gtnumber&lt/code&gt&lt/pre&gt is positive, negative, or zero and prints the corresponding message.&lt/pre&gt&lth2&gtFunctions&lt/h2&gt&ltp&gtFunctions in Kotlin are declared using the &ltcode&gtfun&lt/code&gt keyword. Here’s an example of a simple function that takes two parameters and returns their sum:&lt/pre&gt&ltcode&gtfun add(a: Int, b: Int): Int {
return a + b
}&lt/code&gt&ltpre&gtYou can call this function by passing arguments and using the returned value as needed.&lt/pre&gt