Created
September 29, 2025 14:20
-
-
Save stevdza-san/5c94d3843cc2501b118ae73b7843fe41 to your computer and use it in GitHub Desktop.
Kotlin Basics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Config { | |
companion object { | |
const val APP_NAME = "MyApp" | |
const val VERSION = "1.0" | |
} | |
} | |
//object Config2 { // Error | |
// companion object { | |
// const val APP_NAME = "MyApp" | |
// const val VERSION = "1.0" | |
// } | |
//} | |
object Singleton | |
data object Singleton2 | |
fun main() { | |
println(Config.APP_NAME) // ✅ MyApp | |
println(Config.VERSION) // ✅ 1.0 | |
println(Singleton) | |
println(Singleton2) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Animal( | |
val name: String, | |
var age: Int | |
) | |
class Person1(val name: String) { | |
var age: Int = 0 | |
var address: String = "" | |
constructor( | |
name: String, | |
age: Int | |
) : this(name) { | |
this.age = age | |
} | |
constructor( | |
name: String, | |
age: Int, | |
address: String | |
) : this(name) { | |
this.age = age | |
this.address = address | |
} | |
} | |
class Person2( | |
val name: String, | |
val age: Int, | |
val address: String? = null | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data class Dog( | |
val name: String, | |
val age: Int | |
) | |
fun main() { | |
val dog1 = Dog("Rex", 25) | |
val dog2 = dog1.copy(age = 26) // creates a new instance with updated age | |
// val dog3 = dog1.apply { age = 26 } // Error | |
println(dog1.toString()) // Dog(name=Rex, age=25) | |
println(dog2) // Dog(name=Rex, age=26) | |
println("--") | |
println("Dog1 hash: ${dog1.hashCode()} - Dog2 hash: ${dog2.hashCode()}") | |
println("--") | |
// Destructuring into separate variables | |
val (dogName, dogAge) = dog1 | |
println("Dog name: $dogName") | |
println("Dog age: $dogAge") | |
dog1.component1() | |
dog1.component2() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun main() { | |
// byte, short, int, long | |
// float, double | |
val number = 5 | |
val doubleNumber = 4.99 | |
val floatNumber = 4.99f | |
val letter = 'A' | |
val boolean = true | |
val text = "5" | |
val numberFromString = Integer.parseInt(text) | |
val example = 1 + 1.5 | |
val example2 = 'a' + 5 | |
print(example2) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package basics | |
enum class Color { | |
RED, GREEN, BLUE | |
} | |
fun main() { | |
// Using entries property | |
for (color in Color.entries) { | |
println(color) | |
} | |
// Java implementation | |
val javaImpl = Color.values() | |
// Can throw IllegalArgumentException | |
val greenColor = Color.valueOf(value = "GREEN") | |
// Converting to a list | |
val colorList = Color.entries.toList() | |
println("We have ${colorList.size} colors: $colorList") | |
println("---") | |
// Ordered list | |
Color.entries | |
.map { "${it.ordinal + 1}. ${it.name}" } | |
.forEach { println(it) } | |
} | |
enum class Priority(val color: String) { | |
LOW(color = "Green"), | |
MEDIUM(color = "Orange"), | |
HIGH(color = "Red"); | |
val number: Int | |
get() = when (this) { | |
LOW -> 1 | |
MEDIUM -> 2 | |
HIGH -> 3 | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data class Human( | |
val name: String, | |
val age: Int | |
) { | |
private val secretKey = "This is private" | |
val publicKey = "This is public key" | |
} | |
// Extension function | |
fun Human.showSecret(): String { | |
// return this.secretKey // ❌ ERROR: Cannot access 'secret': it is private in 'User' | |
return "Can't access private properties from extension functions!" | |
} | |
// Extension function | |
fun Human.showPublicKey(): String { | |
return this.publicKey | |
} | |
fun Int.isEven(): Boolean = this % 2 == 0 | |
//public static boolean isEven(int receiver) { | |
// return receiver % 2 == 0; | |
//} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package basics | |
data class User( | |
val name: String, | |
val age: Int, | |
val address: String | |
) { | |
private val secretKey = "This is private" | |
} | |
// Extension property | |
val User.isAdult: Boolean | |
get() = age >= 18 | |
fun main() { | |
val user = User( | |
name = "Stefan", age = 30, | |
address = "Dummy address" | |
) | |
if (user.isAdult) { | |
// Proceed | |
} else return | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun main() { | |
// Different parameter order then defined | |
greetPerson( | |
greeting ="Good morning", | |
name = "Bob" | |
) | |
// | |
// introduce(age = 30, name = "Carol", city = "Paris") | |
} | |
// Basic function | |
fun greet(name: String) { | |
println("Hello, $name!") | |
} | |
// Function with a return value | |
fun add(a: Int, b: Int): Int { | |
return a + b | |
} | |
// Single-expression function | |
fun multiply(a: Int, b: Int) = a * b | |
// Function with Default Parameters | |
fun greetPerson(name: String, greeting: String = "Hello") { | |
println("$greeting, $name!") | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun Int.getNumberType(): NumberType { | |
return if (this > 0) NumberType.Positive | |
else if (this < 0) NumberType.Negative | |
else NumberType.Zero | |
} | |
fun Int.printNumberType() { | |
if (this > 0) println(NumberType.Positive.name) | |
else if (this < 0) println(NumberType.Negative.name) | |
else println(NumberType.Zero.name) | |
} | |
enum class NumberType { | |
Positive, | |
Negative, | |
Zero | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlin.random.Random | |
fun main() { | |
val names = listOf("Alice", "Bob", "Charlie") | |
if ("Bob" in names) { | |
println("Bob is in the list") | |
} | |
val email = "mySecret123" | |
if ('@' !in email) { | |
println("Email must contain @") | |
} else { | |
println("Email is okay") | |
} | |
val day = Random.nextInt(from = 1, until = 10) | |
val typeOfDay = when (day) { | |
in 1..5 -> "Weekday" | |
in 6..7 -> "Weekend" | |
else -> "Invalid day" | |
} | |
println(typeOfDay) | |
} | |
fun Int.isValidAge(): Boolean = when { | |
this !in 18..99 -> false | |
else -> true | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Utils { | |
companion object { | |
@JvmStatic | |
fun greet() = println("Hello") | |
} | |
} | |
object MathUtils { | |
@JvmStatic | |
fun square(x: Int) = x * x | |
} | |
//class MathUtilsNew { | |
// @JvmStatic // Error | |
// fun square(x: Int) = x * x | |
//} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stevdza_san.basics | |
// Function with a lambda as the last parameter | |
fun repeatAction(times: Int, action: (Int) -> Unit) { | |
for (i in 1..times) { | |
action(i) | |
} | |
} | |
// Lambda assigned to a variable | |
val greet: (String) -> String = { name -> "Hello, $name!" } | |
fun main() { | |
repeatAction(times = 3) { | |
println("Printing: $it") | |
} | |
println(greet("Stefan")) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
lateinit var name: String | |
fun main() { | |
if (::name.isInitialized) { | |
println("Name: $name") | |
} else { | |
println("Name is not initialized yet") | |
} | |
// Initialize it | |
name = "Stefan" | |
println("Name: $name") // Error | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Random | |
fun main() { | |
var name = "Stefan" // non-null, can’t hold null | |
var nickname: String? = null | |
// name = null // Error | |
// // Safe call | |
val nicknameLength = nickname?.length // returns Int? (null if nickname is null) | |
println(nicknameLength) | |
// // Elvis operator | |
val displayName = nickname ?: "No nickname" | |
println(displayName) | |
// | |
// // Non-null assertion (Double bang operator) | |
if (Random().nextBoolean()) nickname = "Stevdza-San" | |
println("Nickname length: ${nickname!!.length}") // ⚠️ risky | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//fun foo(a: Int): Int = a | |
//fun foo(a: Int): String = a.toString() // ❌ Error: Conflicting overloads | |
fun welcome() = println("Anonymous") | |
fun welcome(name: String) = println("Hello, $name!") | |
fun welcome(name: String, age: Int) = println("Hello, $name! Age: $age") | |
fun greet( | |
name: String = "Guest", | |
age: Int = 18, | |
address: String? = null | |
) { | |
println("Hello, $name! Age: $age") | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Car { | |
fun start() | |
fun stop() | |
} | |
fun interface Bicycle { | |
fun ride() | |
// fun stop() // Error | |
} | |
fun interface MouseListener { | |
fun onMouseClick(x: Int, y: Int) | |
} | |
val listener = MouseListener { x, y -> println("Clicked at ($x, $y)") } | |
fun main() { | |
val dog = object : Car { | |
override fun start() = println("Starting the car.") | |
override fun stop() = println("Stopping the car.") | |
} | |
val bike = Bicycle { | |
println("Riding a bike.") | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sealed class Vehicle | |
sealed class RequestState<out T> { | |
data object Idle : RequestState<Nothing>() | |
data object Loading : RequestState<Nothing>() | |
data class Success<out T>(val data: T) : RequestState<T>() | |
data class Error(val message: String) : RequestState<Nothing>() | |
fun isLoading(): Boolean = this is Loading | |
fun isError(): Boolean = this is Error | |
fun isSuccess(): Boolean = this is Success | |
fun getSuccessData() = (this as Success).data | |
fun getSuccessDataOrNull() = if (this.isSuccess()) this.getSuccessData() else null | |
fun getErrorMessage(): String = (this as Error).message | |
} | |
fun getRequestedState(state: RequestState<String>) = | |
when (state) { | |
is RequestState.Idle -> "Idle" | |
is RequestState.Loading -> "Loading" | |
is RequestState.Success -> state.data | |
is RequestState.Error -> state.message | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
typealias UserMap = Map<Int, Pair<String, List<String>>> | |
typealias OnItemClick = (String, Int, Boolean) -> Unit | |
fun main() { | |
val userMap: Map<Int, Pair<String, List<String>>> = mapOf() | |
val userMapNew: UserMap = mapOf() | |
val onClick: (String, Int, Boolean) -> Unit = { text, index, isActive -> | |
println("$text at $index is active? $isActive") | |
} | |
val onClickNew: OnItemClick = { text, index, isActive -> | |
println("$text at $index is active? $isActive") | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum class Role { ADMIN, USER, GUEST } | |
fun greet(role: Role): String { | |
return when (role) { | |
Role.ADMIN -> "Hello Admin" | |
Role.USER -> "Hello User" | |
Role.GUEST -> "Hello Guest" | |
// ✅ exhaustive: all enum cases covered, no else needed | |
} | |
} | |
enum class NumberKind { Positive, Negative, Zero } | |
fun Int.getKind() { | |
when { | |
this > 0 -> NumberKind.Positive | |
this < 0 -> NumberKind.Negative | |
else -> NumberKind.Zero | |
} | |
} | |
fun main() { | |
val age = 25 | |
when (age) { | |
in 0..12 -> println("Child") | |
in 13..19 -> println("Teen") | |
in 20..59 -> println("Adult") | |
else -> println("Senior") | |
} | |
val input: Any = "Kotlin" | |
val result = when (input) { | |
is Int -> when { | |
input < 0 -> "Negative integer" | |
input in 0..10 -> "Small integer" | |
input * 2 > 50 -> "Large when doubled" | |
else -> "Other integer" | |
} | |
is String -> when { | |
input.length == 0 -> "Empty string" | |
input.length < 5 -> "Short string" | |
input.contains("lin") -> "Contains 'lin'" | |
else -> "Regular string" | |
} | |
is Double -> when { | |
input < 0.0 -> "Negative double" | |
input > 100.0 -> "Big double" | |
else -> "Other double" | |
} | |
else -> "Unknown type" | |
} | |
println(result) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment