Kotlin Basics: A Quick Guide

Kotlin Basics: A Quick Guide

Read Time:5 Minute, 55 Second

Kotlin Playground (https://play.kotlinlang.org) is an online editor where you can write, run, and share Kotlin code in your browser — no setup needed. It supports Kotlin on JVM/JS, shows results in a console, and lets you share snippets via link.

Content

  1. println() v print()
  2. val & var
    1. Strings and Booleans
    2. Numbers
    3. Displaying Variables
  3. Operators
    1. Numbers
    2. Assignments
    3. Comparisons
    4. Logical
  4. Strings
    1. Access a String
    2. String Length
    3. String Functions
    4. Comparing Strings
    5. Finding a String in a String
    6. Quotes Inside a String
    7. Escape Characters
    8. String Concatenation
  5. Control Flow / Conditions
    1. If .. Else
    2. Ternary
    3. When
    4. While
    5. Do while
  6. Arrays
    1. Access
    2. Change
    3. Length / Size
    4. Exist
    5. For
    6. Range
  7. Assertion Methods
  8. Functions
    1. Parameters
    2. return x
    3. return x + y
    4. eturn x + y (short)
  9. Objected Oriented Programming
    1. Class
    2. Create Object from class
    3. Access the properties and add some values
    4. Constructor Method
    5. Superclass
    6. Subclass
    7. Create an object of MyChildClass and call myFunction

 

1. println() v print()

println("Hello World!")
println("I am learning Kotlin.")
println("It is awesome!")
println(3 + 3)
println("Hello" + " - " + "World") // This is a comment

print("Hello World! ")
print("I am learning Kotlin. ")
print("It is awesome!")

println("""
    println("Hello World!")
    println("I am learning Kotlin.")
    println("It is awesome!")
    println(3 + 3)
    println("Hello" + " - " + "World") // This is a comment
""")

2. val & var

  • Data Types, Define Variables, & Update Variables
  • camelCase: variables, functions, properties. val studentName = "Alice"
  • PascalCase: classes, objects. class StudentProfile { }, object NetworkManager { }
  • UPPER_SNAKE_CASE: constants. const val MAX_USERS = 100
  • lowercase: packages. package com.example.myapp
  • Types: Int, Double, Char, Boolean, Strings, Arrays
  • Convert: toByte(), toShort(), toInt(), toLong(), toFloat(), toDouble(), toChar()

val myNum = 5 // Int
val myDoubleNum = 5.99 // Double
val myLetter = 'D' // Char
val myBoolean = true // Boolean
val myText = "Hello" // String

val myNum: Int = 5 // Int
val myDoubleNum: Double = 5.99 // Double
val myLetter: Char = 'D' // Char
val myBoolean: Boolean = true // Boolean
val myText: String = "Hello" // String

— Strings and Booleans


var name = "John" // String (text)
val birthyear = 1975 // Int (number)
println(name) // Print the value of name
println(birthyear) // Print the value of birthyear

var name: String = "John" // String
val birthyear: Int = 1975 // Int
println(name)
println(birthyear)

val isKotlinFun: Boolean = true
val isFishTasty: Boolean = false
println(isKotlinFun) // Outputs true
println(isFishTasty)

// declare without assigning value
var ming: String
ming = "John"
println(ming)

/* Will not work:
var name
name = "John"
println(name)
*/

— Numbers

  • Int: -2,147,483,648 to 2,147,483,647
  • Byte: -128 to 127
  • Short: 32768 to 32767
  • Long: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 OR End with L
  • Float: 6 decimals Or End with F
  • Double: 15 decimals / 1.7976931348623157E308
val myNum: Int = 5

— Displaying Variables

println("Hello " + name)

val lastName = "Doe"
val fullName = name + ' ' + lastName
println(fullName)

3. Operators

— Numbers

+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus / remainder x % y
++ Increment ++x
-- Decrement --x

— Assignments

= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3

— Comparisons

== Equal to x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y >= Greater than or equal to x >= y
<= Less than or equal to x <= y

— Logical

&& and
|| or
! not / reverse

4. Strings

var greeting = "Hello"
var greeting: String = "Hello"
var name: String
name = "John"
println(name)

— Access a String

var txt = "Hello World"
println(txt[0]) // first element (H)
println(txt[2]) // third element (l)

— String Length

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
println("The length of the txt string is: " + txt.length)

— String Functions

var txt = "Hello World"
println(txt.toUpperCase()) // Outputs "HELLO WORLD"
println(txt.toLowerCase()) // Outputs "hello world"

— Comparing Strings

var txt1 = "Hello World"
var txt2 = "Hello World"
println(txt1.compareTo(txt2)) // Outputs 0 (they are equal)

— Finding a String in a String

var txt = "Please locate where 'locate' occurs!"
println(txt.indexOf("locate")) // Outputs 7

— Quotes Inside a String

var txt1 = "It's alright"
var txt2 = "That's great"

— Escape Characters

var txt = "We are the so-called \"Vikings\" from the north."
println(txt)

— String Concatenation

var firstName = "John"
var lastName = "Doe"
println(firstName + " " + lastName)

var firstName = "John "
var lastName = "Doe"
println(firstName.plus(lastName))

5. Control Flow / Conditions

— If .. Else

val time = 20
val greeting = if (time < 18) { "Good day." } else { "Good evening." } println(greeting)

— Ternary

val time = 20
val greeting = if (time < 18) "Good day." else "Good evening." println(greeting)

— When

val day = 4

val result = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid day."
}
println(result)

// Outputs "Thursday" (day 4)

— While

Checks the condition first.

var i = 0
while (i < 10) { println(i) i++ if (i == 4) { break // break } } var i = 0 while (i < 10) { if (i == 4) { i++ continue // continue } println(i) i++ }

— Do while

Execute at least once

var i = 0
do {
println(i)
i++
}
while (i < 5)

6. Arrays

— Access

val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
println(cars[0])
// Outputs Volvo

— Change

val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
cars[0] = "Opel"
println(cars[0])
// Now outputs Opel instead of Volvo

— Length / Size

val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
println(cars.size)
// Outputs 4

— Exist

val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
if ("Volvo" in cars) {
println("It exists!")
} else {
println("It does not exist.")
}

val nums = arrayOf(2, 4, 6, 8)
if (2 in nums) {
println("It exists!")
} else {
println("It does not exist.")
}

— For

i.e. loop

val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
for (x in cars) {
println(x)
}

— Range

e.g Range

for (chars in 'a'..'x') {
println(chars)
}

for (nums in 5..15) {
println(nums)
}

for (nums in 5..15) {
if (nums == 10) {
break // break
}
println(nums)
}

for (nums in 5..15) {
if (nums == 10) {
continue // continue
}
println(nums)
}

7. Assertion Method

  • assertEquals(expected, actual) → check equality
  • assertNotEquals(unexpected, actual) → check not equal
  • assertTrue(condition) → condition must be true
  • assertFalse(condition) → condition must be false
  • assertNull(value) → value must be null
  • assertNotNull(value) → value must not be null
  • assertSame(expected, actual) → they must be the same object
  • assertNotSame(unexpected, actual) → not the same object
  • fail("message") → force a failure (useful if some code should not be reached)
class ExampleUnitTest { // Object Oriented Programming: Class (car), Object (open, proton, volvo)
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}

class ModifiedUnitTest {
@Test
fun addition_isIncorrect() {
assertEquals(4, 1 + 2)
}
}

fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}

8. Functions

fun myFunction() {
println("I just got executed!")
}

fun main() {
myFunction()
myFunction()
myFunction()
}

// I just got executed!
// I just got executed!
// I just got executed!

— Parameters

fun myFunction(fname: String) {
println(fname + " Doe")
}

fun main() {
myFunction("John")
myFunction("Jane")
myFunction("George")
}

// John Doe
// Jane Doe
// George Doe

fun myFunction(fname: String, age: Int) {
println(fname + " is " + age)
}

fun main() {
myFunction("John", 35)
myFunction("Jane", 32)
myFunction("George", 15)
}

// John is 35
// Jane is 32
// George is 15

— return x

fun myFunction(x: Int): Int {
return (x + 5)
}

fun main() {
var result = myFunction(3)
println(result)
}

// 8 (3 + 5)

— return x + y

fun myFunction(x: Int, y: Int): Int {
return (x + y)
}

fun main() {
var result = myFunction(3, 5)
println(result)
}

// 8 (3 + 5)

— return x + y (short)

fun myFunction(x: Int, y: Int) = x + y

fun main() {
var result = myFunction(3, 5)
println(result)
}

// 8 (3 + 5)

9. Objected Oriented Programming

— Class

class Car {
var brand = ""
var model = ""
var year = 0
}

— Create Object from class

class Car {
var brand = ""
var model = ""
var year = 0
}

val c1 = Car()

— Access the properties and add some values

c1.brand = "Ford"
c1.model = "Mustang"
c1.year = 1969

println(c1.brand) // Outputs Ford
println(c1.model) // Outputs Mustang
println(c1.year) // Outputs 1969

val c1 = Car()
c1.brand = "Ford"
c1.model = "Mustang"
c1.year = 1969

val c2 = Car()
c2.brand = "BMW"
c2.model = "X5"
c2.year = 1999

println(c1.brand) // Ford
println(c2.brand) // BMW

— Constructor Method

class Car(var brand: String, var model: String, var year: Int)

fun main() {
val c1 = Car("Ford", "Mustang", 1969)
val c2 = Car("BMW", "X5", 1999)
val c3 = Car("Tesla", "Model S", 2020)
}

— Superclass

open class MyParentClass {
val x = 5
}

— Subclass

class MyChildClass: MyParentClass() {
fun myFunction() {
println(x) // x is now inherited from the superclass
}
}

— Create an object of MyChildClass and call myFunction

fun main() {
val myObj = MyChildClass()
myObj.myFunction()
}

Note: Most code examples are adapted from W3Schools for educational purposes.

Leave a Reply

Your email address will not be published. Required fields are marked *

Exploring Mind Map Apps for Family-Friendly Flexibility: A Review Previous post Exploring Mind Map Apps for Family-Friendly Flexibility: A Review
Android Studio Basics: A Quick Guide Next post Android Studio Basics: A Quick Guide