Programming Basics using Kotlin
Kotlin Basics that all developer should learn before diving into intermediate and advanced topics.
Entry point
main
function is the entry point to the Kotlin program.
main
function is automatically invoked when Kotlin program is executed
main
function can contain a parameter or be empty
if main
function contain’s a parameter then the type of the parameter should be Array<String>
Using val and var
val
means value. It can be initialized and it cannot be reassigned.
var
mean variable and it is mutable
Syntax
val identifier = initalization
var identifier = initalization
identifier
refers to elements in a program
Data types
Each data has a type. Kotlin has predefined data types such as
- Numbers - Int, Float, Literal Constants
- Characters
- Strings
- Booleans
- Arrays
- Unsigned Integer types - No negative value
Integer types
- Byte —> 8 bit values between -128 to 127
- Short –> 16 bit values between -32768 to 32767
- Int ——> 32 bit values between -231 to 231 -1
- Long —> 64 bit
Floating point type
- Float - single precision - 6 to 7 decimal points
- Double - double precision - 15 to 16 decimal points
Literal Constants
- Decimal - 126
- Long - 12490L
- Hexadecimal - 0x0F
- Binary - 0b00001011
Characters
Characters are represented by the type Char
Special characters start from an escaping backslash
-
\t
– tab -
\b
– backspace -
\n
– new line (LF) -
\r
– carriage return (CR) -
\'
– single quotation mark -
\"
– double quotation mark -
\\
– backslash -
\$
– dollar sign
Adding Int to a Char yields another Char
Boolean
&&
(AND) logicalAND
or conjunction||
(OR) logicalOR
or disjunction!
(NOT) logicalNOT
or negation
Assignment Operators
Increment and Decrement Operators
For post increment, i++
first produce the result, then do the increment.
- Store the initial value of
i
to a temporary storagei0
. - Assign the result of
i0.inc()
toi
. - Return
i0
as the result of the expression. That is whyj
value is 0
For pre increment, ++k
first do the increment, then return the resulting value.
- Assign the result of
k.inc()
tol
. - Return the new value of
l
as a result of the expression.
Ranges
- Using for loop with
in
keyword - Using Ranges with help of
..
,until
,downTo
,step
- Looping Char
a
..z
- Find Char in String using
in
keyword
Using in
keyword
in
can be used for iteration in for loops and to check membership.
Expression
Expression yields result
Example for expression: if-else as an expression
Statement
Statement create side effect and doesn’t produce result
Example for statement: for loop