Exploring Basic Kotlin Syntax and Structure - Day 2 Android 14 Masterclass
Exploring Basic Kotlin Syntax and Structure - Day 2 Android 14 Masterclass
In Kotlin, variables can be defined using either var or val keyword, followed by
the variable name, an optional data type, and an assignment. The assignment
operator is represented by the equals sign (=). The assignment operator is used to
assign a value to a variable.
val: Stands for “value” and it’s immutable, which means once you assign a value to
a val variable, you cannot change or reassign it.
Preferred when you have a variable whose value shouldn’t change once initialized,
like constants or properties that should remain unchanged.
Used when you anticipate the value of a variable will change, like counters in a
loop or a value being updated based on user input.
When you’re programming, you work with different kinds of information or data,
like numbers, words, or true/false values. Datatypes in Kotlin are like labels that tell
the computer what kind of data you’re dealing with so it knows how to handle them
properly.
You need to tell the computer the datatype of your information (like number, word,
true/false) when you first create a variable. Once you set the type, it stays the same.
Description: Integer types can hold whole numbers, both positive and negative.
The most commonly used integer type is Int.For larger integer values, Long can be
used.
Syntax and Examples:
Description: Booleans are like light switches in programming. They can only have
two values: true (on) or false (off). They are used to make decisions in code,
allowing parts of your program to run based on whether a condition is true or false.
Logical Operators:
Evaluation:
o | always evaluates both operands.
o || performs short-circuit evaluation, skipping the second operand if the
first is true.
Use Cases:
o | is versatile, used for bitwise or logical OR operations.
o || is solely used for logical OR operations to control the flow of
programs based on conditions.
Efficiency:
o || can be more efficient due to short-circuit evaluation, as it may skip
the evaluation of the second operand.
o |might be slightly less efficient in logical operations as it always
evaluates both operands.
Char
The char data type in Kotlin represents a single character. A character could be a
letter, a number, a punctuation mark, or even a symbol like $ or &. Let’s break it
down!
Characters in Kotlin can also represent Unicode characters, allowing you to use a
wide range of symbols and letters from various languages.
Example:
There are also special escape characters in Kotlin, which allow you to represent
special values such as a new line or a tab.
Example:
Strings are sequences of characters enclosed within double quotes (” “). They are
used to manage and manipulate text in Kotlin.
Strings are immutable, meaning once a string is created, it cannot be changed, but
you can create a new string based on modifications of the original string.
3. Type Conversion
Type conversion, also known as type casting, is a process where the type of a
variable is converted to another datatype. Explicit conversion is often necessary
when you want to work with variables of incompatible types together.
Numbers:
You might want to convert between different number types, like from Int to Double,
or Long to Int.
Numbers can be converted to strings when you want to display them as text or
concatenate them with other strings.
If a string contains a number, you can convert that string into an actual number type,
like Int or Double.
4. User Input
Getting input from the user is essential in programming when you want your
application to interact with the user by receiving data that the user provides. In
Kotlin, you can receive user input from the console using the standard library
functions, making your programs interactive and dynamic.
If you want to ask the user for input and display it, you can use the combination
of println() to show a message and readLine() to get the user’s response.
if and else if statements are used in Kotlin to make decisions in your code based
on conditions. They allow your program to execute different blocks of code based
on whether certain conditions are true or false.
if Statement:
An if statement checks a condition and executes a block of code if that condition
is true.
1 val age = 20
2
3 if (age >= 18) {
4 println("You are eligible to vote.")
5}
6
In this example, since the age is 20 (which is greater than or equal to 18), the
message “You are eligible to vote.” will be printed to the console.
1 val age = 15
2
3 if (age >= 18) {
4 println("You are eligible to vote.")
5 } else {
6 println("You are not eligible to vote.")
7}
8
Here, because the age is 15 (which is less than 18), the condition in the if statement
is false, so the message “You are not eligible to vote.” will be printed.
1 val number = 0
2
3 if (number > 0) {
4 println("The number is positive.")
5 } else if (number == 0) {
6 println("The number is zero.")
7}
8
In this example, since the number is not greater than 0, it checks the next condition
(number == 0), which is true, so it prints “The number is zero.”
1 val number = -5
2
3 if (number > 0) {
4 println("The number is positive.")
5 } else if (number < 0) {
6 println("The number is negative.")
7 } else {
8 println("The number is zero.")
9}
10
Here, the program checks multiple conditions:
Example:
1 val number = 2
2
3 when (number) {
4 1 -> println("It is one.")
5 2 -> println("It is two.")
6 3 -> println("It is three.")
7 else -> println("It is not one, two, or three.")
8}
9
Imagine you have a robot that can repeat a task for you, like clapping hands or
counting numbers. A while loop in Kotlin is like that robot. It keeps doing a task
over and over as long as a certain condition is true.
How It Works:
Let’s say you want the robot to clap hands five times. You can tell the robot:
If you forget to tell the robot when to stop (like forgetting the count++), the robot will
keep clapping hands forever!
This is called an “infinite loop,” and it can make your program run forever and not
work correctly.
So, a while loop helps you repeat tasks in your code, but remember to always give it
a stopping condition! More examples:
1 var number = 1
2 while (number <= 10) {
3 println("Number: $number")
4 number++ // Don't forget this part! It makes sure the loop won’t go on forever.
5}
6
In this example, as long as the variable number is less than or equal to ten, it will
keep printing the number and then adding one to it.
Countdown
1 var countdown = 5
2 while (countdown > 0) {
3 println("Countdown: $countdown")
4 countdown--
5}
6 println("Blast off!")
7
Here, the loop starts at five and counts down, subtracting one each time until it gets
to one. Then it prints “Blast off!”
Operators are special symbols or keywords that are used to perform operations.
You have already seen some operators in the boolean section of this summary and
in the code examples.
Arithmetic Operators
Addition +: 5 + 3 results in 8
Subtraction : 5 - 3 results in 2
Multiplication : 5 * 3 results in 15
Division /: 5 / 2 results in 2.5
Modulus %: 5 % 2 results in 1 (Remainder of 5 divided by 2)
Comparison Operators
Equals =: val x = 5
Plus Equals +=: x += 3 (Equivalent to x = x + 3)
Minus Equals =: x -= 3 (Equivalent to x = x - 3)
Multiply Equals =: x *= 3 (Equivalent to x = x * 3)
Divide Equals /=: x /= 3 (Equivalent to x = x / 3)
Logical Operators
Day 3:-
Skip to content
Subscribe
Courses
Blog
Contact
Member Area
Functions are the building blocks of a Kotlin program. They carry out specific tasks
and can be reused throughout the code. In this section, we’ll learn how to define
and call functions in Kotlin, making your journey in Kotlin programming smoother and
more efficient.
Function: A self-contained module that you can reuse and run as many times
as needed. It can receive input data and return an output.
Parameter: Data that you pass into a function. It’s used within the function to
accomplish a task.
Return Type: The type of value that a function gives back when it’s called.
Syntax Explanation:
A function is declared using the fun keyword followed by a name that describes its
task. The function might take parameters as input enclosed in parentheses () and
return a value.
Functions’ names
Print Statement:
Key Points:
return is used inside a function to exit it and pass back a value to where the
function was called. A function that has a return type must use the return statement
to give back a value.
Value Returning: It passes a value back to where the function was called.
Exits Function: Once a return statement is executed, the function stops
running, and control is returned to the caller.
Specifies Output: Defines the outcome of a function that can be used
elsewhere in the program.
1 fun add(a: Int, b: Int): Int {
2 return a + b
3}
4
5 val result = add(2, 3)
6 println(result) // Output: 5
7
Here, add(2, 3) returns 5, which is stored in the variable result and then printed.
In a Nutshell:
Use print when you want to see the output or state of the program on the
console.
Use return when you want your function to produce a value that will be used
later in the code.
2. Classes and Objects: Exploring Basic Kotlin Syntax
Objects are instances of classes, where the class defines certain attributes
(properties) and behaviors (functions/methods) that its objects will have.
Syntax Explanation
A basic class definition looks like this:
1 class ClassName {
2 // class body
3}
4
Initializer Block
1 class Person(name: String, age: Int) {
2 val name = name
3 val age = age
4
5 init {
6 println("Person named $name is created.")
7 }
8}
9
In this example, the init block will run as soon as an object of Person class is
created, printing a message to the console.
Default Values
1 class Person(val name: String = "John", val age: Int = 30)
2
Here, the properties name and age have default values. If no values are provided
when creating an object, these defaults will be used.
Creating Objects/Instances
1 val person1 = Person("Alice", 25)
2 val person2 = Person()
3
person1 is an object of Person, created with specific values, while person2 uses the
default values.
Parameter: A value you pass into the constructor when creating an object.
E.g., "Alice" and 25 in Person("Alice", 25).
Property: A variable within the class where the passed or default values are
stored. E.g., val name and val age in the Person class.
Data classes are concise ways to create classes used mainly for holding data.
If you want to skyrocket your Android career, check out our The Complete Android
14 & Kotlin Development Masterclass. Learn Android 14 App Development From
Beginner to Advanced Developer.