0% found this document useful (0 votes)
27 views

Exploring Basic Kotlin Syntax and Structure - Day 2 Android 14 Masterclass

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Exploring Basic Kotlin Syntax and Structure - Day 2 Android 14 Masterclass

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Day:-2

Exploring Basic Kotlin Syntax and


Structure – Day 2 Android 14
Masterclass
Welcome to Day 2 of our Android 14 Masterclass, where we dive into the Basic
Kotlin Syntax and Structure. As you embark on this coding journey, understanding
Kotlin’s syntax and structure is paramount. Today, we’re peeling back the layers of
this intuitive language, starting with variables and data types, maneuvering through
user input and control flows, and mastering loops and operators. Whether you’re a
seasoned developer or a novice in the app-making realm, our guide will solidify your
foundation and equip you with the essential tools for crafting robust Android
applications.

1. What are Variables?

Variables are fundamental building blocks in Kotlin programming (and programming


in general), allowing developers to store, modify, and manage data within their
applications. Variables can hold various types of data, such as numbers, characters,
strings, or even more complex data structures like lists or objects.

Creating Variables: Exploring Basic Kotlin Syntax and Structure

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.

1 var variableName: DataType = value // Mutable variable (can change value)


2 val constantName: DataType = value // Immutable (Read-only) variable
3
More examples:

1 var age: Int = 30 // Mutable integer variable


2 val pi: Double = 3.14 // Immutable double variable
3 var name = "John Doe" // Type inferred as String, Mutable
4 val isAdult = true // Type inferred as Boolean, Immutable
5
val vs. var :

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.

1 val pi = 3.14 // An immutable variable


2 // pi = 3.14159 // This would cause a compilation error
3
var: Is mutable, meaning after you assign an initial value, you can change or
reassign that variable to a new value as many times as you want.

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.

1 var counter = 0 // A mutable variable


2 counter = 1 // Modifying the value of the variable
3

2. What are Datatypes?

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.

Integers (Int and Long)

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:

1 val age: Int = 25


2 val largeNumber: Long = 10000000000L
3
Floats and Doubles (Float and Double)

Description: Floats and Doubles are used to represent decimal


numbers. Double has higher precision and is generally used as the default for
decimal numbers.

Syntax and Examples:

1 val pi: Double = 3.14


2 val floatNumber: Float = 2.73F
3
Booleans (Boolean)

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:

 || (Logical OR): Returns true if at least one condition is true.


 && (Logical AND): Returns true only if both conditions are true.
 ! (Logical NOT): Negates the value; turns true into false and vice versa.
Syntax and Examples:

1 val isTrue = true


2 val isFalse = false
3
1 val result1 = isTrue || isFalse // Logical OR, result1 will be true
2 val result2 = isTrue && isFalse // Logical AND, result2 will be false
3 val result3 = !isTrue // Logical NOT, result3 will be false
4
| vs. || Operators
Both | and || operators are used with boolean values (true or false) in Kotlin,
but they serve different purposes and behave differently.

 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 are surrounded by single quotes (' ').

1 val letter: Char = 'A'


2 val number: Char = '1'
3 val symbol: Char = '$'
4
Unicode Characters:

Characters in Kotlin can also represent Unicode characters, allowing you to use a
wide range of symbols and letters from various languages.

Example:

1 val heart: Char = '\\u2764'


2 println(heart) // Output: ❤
3
Special Characters:

There are also special escape characters in Kotlin, which allow you to represent
special values such as a new line or a tab.

Example:

 New line: '\\n' – moves to the next line


 Tab: '\\t' – adds a tab space
Strings

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.

1 val simpleString: String = "Hello, World!”


2
String Concatenation:

Strings can be joined together using the + operator.

1 val firstName = "John"


2 val lastName = "Doe"
3 val fullName = firstName + " " + lastName // "John Doe"
4

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.

Common Type Conversions

Numbers:
You might want to convert between different number types, like from Int to Double,
or Long to Int.

1 val integer: Int = 5


2 val double: Double = integer.toDouble() // converting Int to Double
3
Numbers to Strings:

Numbers can be converted to strings when you want to display them as text or
concatenate them with other strings.

1 val number: Int = 42


2 val stringNumber: String = number.toString() // converting Int to String
3
Strings to Numbers:

If a string contains a number, you can convert that string into an actual number type,
like Int or Double.

1 val stringNumber = "123"


2 val intNumber: Int = stringNumber.toInt() // converting String to Int
3

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.

Here’s a simple way to do it:

1println("What is your name?") // Display a message to the user with println()


2
3 val userName = readLine() // Get the user’s response with readLine()
4
5 println("Hello, $userName!") // Show the user’s response with println()
6

5. Basic Kotlin Syntax – Understanding if and else


if Statements

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.

 The if-else Statement:


You can use an else statement following an if statement to execute a block of code
when the condition in the if statement is false.

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.

 The else if Statement:


An else if statement follows an if statement and checks another condition if the
previous condition was false.

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

Combining if, else if, and else:


You can combine if, else if, and else to handle multiple conditions and a default
case.

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:

 If the number is positive, it prints “The number is positive.”


 If the number is negative (which it is), it prints “The number is negative.”
 If none of the above conditions are true, it defaults to printing “The number is
zero.”
6. Basic Kotlin Syntax
– Understanding when Statements

 when is like a decision-maker in your code.


 You give when a value, and it picks a result based on that value.
 It makes your code cleaner and easier to understand when you have many
choices.
So, you can think of the when statement as a smarter, more organized way of making
decisions in your code compared to the if statement!

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

7. Basic Kotlin Syntax – Understanding while Loops

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:

1. Start counting from one.


2. Clap your hands.
3. If you haven’t clapped five times, go back to step 2.
In Kotlin, you write this like:

1 var count = 1 // Step 1: Start counting from one


2
1 while (count <= 5) { // As long as you haven’t clapped five times
2 println("Clap hands!") // Step 2: Clap your hands
3 count++ // Go back to step 2 if you haven’t clapped five times
4}
5
Warning: Be Careful of Infinite Loops!

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:

Basic Kotlin Syntax for Counting to Ten

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!”

8. Basic Kotlin Syntax – Operators

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.

Let’s discuss some common categories of operators:

Arithmetic Operators

These are used for mathematical operations:

 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

These operators compare two values:

 Equals ==: 5 == 3 results in false


 Not Equals !=: 5 != 3 results in true
 Greater Than >: 5 > 3 results in true
 Less Than <: 5 < 3 results in false
 Greater Than or Equal To >=: 5 >= 5 results in true
 Less Than or Equal To <=: 5 <= 3 results in false
Assignment Operators
Used to assign values to variables:

 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

Used for boolean logic (true or false values):

 AND &&: true && false results in false


 OR ||: true || false results in true
 NOT !: !true results in false

Conclusion: Exploring Basic Kotlin Syntax and Structure – Day 2


Android 14 Masterclass

As we wrap up Day 2 of our Android 14 Masterclass, we’ve journeyed through the


essential Basic Kotlin Syntax and structures that make Kotlin such a powerful and
efficient tool for developers. From the versatility of variables to the logic of control
statements and the persistence of loops, we’ve covered a breadth of fundamental
concepts that are crucial for creating dynamic Android apps. Remember, these
building blocks are just the starting point; with practice, you’ll continue to hone your
skills and unlock the full potential of Kotlin in your Android development adventures.
Keep experimenting, coding, and learning – your path to becoming a Kotlin
connoisseur is well underway!

Day 3:-

Skip to content

 Subscribe
 Courses
 Blog
 Contact
 Member Area

Basic Kotlin Syntax: Functions, Objects


and Classes – Day 3 Android 14 Masterclass
 by Liza Cheremisina
 9. November 2023

Basic Kotlin Syntax: Functions, Objects


and Classes – Day 3 Android 14 Masterclass
Welcome to Day 3 of our Android 14 Masterclass, where we delve into
the essential Kotlin programming concepts of functions, objects, and
classes. Through our detailed exploration of basic Kotlin syntax and practical coding
conventions, you’ll learn the intricacies of building solid and reusable code using
functions, and you’ll get acquainted with object-oriented principles by creating robust
classes and objects. Whether you are starting your journey in Android development
or looking to refine your Kotlin expertise, this post is your one-stop reference for
understanding how Kotlin’s features can be employed to develop cutting-edge
Android applications.
1. Functions

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.

Key Concepts and Terminologies: Exploring Basic Kotlin Syntax

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

1 fun functionName(parameter1: Type, parameter2: Type): ReturnType {


2 // Code to execute
3 return value // value should match ReturnType
4}
5
Naming Conventions: Exploring Basic Kotlin Syntax

Functions’ names

 Camel Case: Function names should be written in camelCase, starting with a


lowercase letter, and then capitalizing each subsequent word without spaces.
 Descriptive: Names should be verbs and precisely describe the function’s
behavior, indicating the action that the function performs.
Avoid Abbreviations: Try to avoid abbreviations unless they are universally

accepted.
Parameter Names:
 Camel Case: Similar to function names, parameter names should also follow
the camelCase convention.
Descriptive: Parameter names should be descriptive enough to indicate the

kind of value expected.
Boolean Functions and Properties:

Prefixed: Boolean functions and properties often start with prefixes



like is, has, are, etc., to make them clearly understandable as returning a
boolean value.
General Tips:

 Consistency: Maintain consistency in naming across the whole project to keep


the codebase clean and understandable.
 Clarity: The name should convey the function’s purpose or the result it will
achieve.
Brevity: While names should be descriptive, they also need to be concise. Find

a balance that maintains clarity without being overly verbose.
Examples:

 Function without parameters and return value


1 fun displayMessage() {
2 println("Hello, Kotlin Learner!")
3}
4
5 // Calling the function
6 displayMessage() // Output: Hello, Kotlin Learner!
7
Here, displayMessage is a simple function that takes no parameters and has no
return value. It prints a message when called.

 Function with parameters and without return value


1 fun greet(name: String) {
2 println("Hello, $name!")
3}
4
5 // Calling the function
6 greet("John") // Output: Hello, John!
7
In this example, greet is a function that takes a String parameter name. It prints a
personalized greeting.
 Function with parameters and a return value
1 fun addNumbers(a: Int, b: Int): Int {
2 return a + b
3}
4
5 // Calling the function
6 val sum = addNumbers(5, 3)
7 println(sum) // Output: 8
8
Here, addNumbers is a function that takes two Int parameters and returns their sum
as an Int.

Print vs. Return

Print Statement:

print or println (print line) is a function used to display information to the


console. When you use print, it displays the text or data you put inside the
parentheses immediately. It’s mainly used for debugging purposes or to give
information about the program’s state.

Key Points:

 Display Output: It shows the output immediately on the console.


 No Effect on Function Flow: Using print does not affect the flow of a function.
The function continues to execute subsequent lines of code.
 Debugging: Helps in tracking the flow and state of a program during
development.
1 fun showMessage() {
2 println("Hello, Kotlin Learner!")
3}
4
5 showMessage() // Output: Hello, Kotlin Learner!
6
In this example, calling showMessage() displays “Hello, Kotlin Learner!” on the
console.
Return Statement:

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.

Key Points about return:

 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

A class is like a blueprint or a template for creating objects.

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

Key Concepts and Terminologies: Exploring Basic Kotlin Syntax

 Constructor: A special function used to initialize the properties of an object


when it’s created. It’s declared in the class header.
 Properties: Variables that are defined in the class to hold some data. They
represent the state of an object.
 Initializers: Code blocks that run when an object is instantiated, used to set up
initial states.
 Objects/Instance: An individual instance created from the class, holding
specific data in its properties.
Detailed Breakdown with Examples:

 Constructor and Properties


1 class Person(name: String, age: Int) {
2 val name = name
3 val age = age
4}
5
Here, Person has a constructor that takes name and age as parameters, and it
initializes the properties with the same names.

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

Property vs. Parameter

 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: Exploring Basic Kotlin Syntax

Data classes are concise ways to create classes used mainly for holding data.

1 data class Person(val name: String, val age: Int)


2
Data classes automatically generate useful functions like toString(), equals(),
and hashCode().

Key Features of Data Classes:


 Immutability: Data classes encourage the use of immutable properties, making
them excellent choices for representing simple immutable data.
 Standard Methods: Kotlin automatically provides implementations of
fundamental methods.
 Destructuring Declarations: They allow you to decompose the data class into
its properties.

Conclusion: Basic Kotlin Syntax: Functions, Objects and Classes – Day 3


Android 14 Masterclass

In wrapping up Day 3 of our Android development masterclass, we’ve demystified


the uses of functions, print and return statements, as well as the principles behind
classes and objects in Kotlin. This article served as a practical guide for mastering
these fundamental concepts of basic Kotlin syntax. By now, you should feel
confident in defining functions with various parameters, recognizing the power of
constructors in class creation, and appreciating the simplicity of data classes for
managing state.

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.

Master Jetpack Compose to harness the cutting-edge of Android


development, gain proficiency in XML — an essential skill for numerous
development roles, and acquire practical expertise by constructing real-world
applications.

ublished. Required fields are marked *

You might also like