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

Kotlin: 100 Simple Codes

The document provides a comprehensive overview of Kotlin programming concepts, including basic syntax, control structures, data types, functions, classes, and advanced features like generics and extension functions. Each concept is illustrated with code examples, demonstrating practical usage and functionality. The document serves as a guide for beginners to learn Kotlin programming effectively.

Uploaded by

Souhail Laghchim
Copyright
© Public Domain
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

Kotlin: 100 Simple Codes

The document provides a comprehensive overview of Kotlin programming concepts, including basic syntax, control structures, data types, functions, classes, and advanced features like generics and extension functions. Each concept is illustrated with code examples, demonstrating practical usage and functionality. The document serves as a guide for beginners to learn Kotlin programming effectively.

Uploaded by

Souhail Laghchim
Copyright
© Public Domain
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

1.

Hello World
Kotlin:

fun main() {
println("Hello, World!")
}

2. Variables and Constants


Kotlin:

fun main() {
var name = "Alice"
val age = 25
println("Name: $name, Age: $age")
}

3. If-Else Statement
Kotlin:

fun main() {
val number = 10
if (number > 5) {
println("Greater than 5")
} else {
println("5 or less")
}
}

4. When Statement (Switch)


Kotlin:

fun main() {
val day = 3
when (day) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday")
else -> println("Another day")
}
}
5. For Loop
Kotlin:

fun main() {
for (i in 1..5) {
println(i)
}
}

6. While Loop
Kotlin:

fun main() {
var i = 1
while (i <= 5) {
println(i)
i++
}
}

7. Functions
Kotlin:

fun greet(name: String) {


println("Hello, $name!")
}

fun main() {
greet("Bob")
}

8. Return Value from Function


Kotlin:

fun add(a: Int, b: Int): Int {


return a + b
}

fun main() {
println(add(5, 3))
}
9. Array Example
Kotlin:

fun main() {
val numbers = arrayOf(1, 2, 3, 4, 5)
for (num in numbers) {
println(num)
}
}

10. List Example


Kotlin:

fun main() {
val fruits = listOf("Apple", "Banana", "Cherry")
for (fruit in fruits) {
println(fruit)
}
}

11. Mutable List


Kotlin:

fun main() {
val numbers = mutableListOf(1, 2, 3)
numbers.add(4)
println(numbers)
}

12. Map Example


Kotlin:

fun main() {
val map = mapOf("name" to "Alice", "age" to 25)
println(map["name"])
}
13. Mutable Map
Kotlin:

fun main() {
val map = mutableMapOf("name" to "Bob", "age" to "30")
println(map)
}

14. Class Example


Kotlin:

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

fun main() {
val person = Person("Alice", 25)
println("${person.name} is ${person.age} years old.")
}

15. Constructor with Default Value


Kotlin:

class Dog(val name: String = "Unknown")

fun main() {
val dog = Dog()
println(dog.name)
}

16. Nullable Variable


Kotlin:

fun main() {
var name: String? = "Alice"
name = null
println(name)
}
17. Safe Call Operator
Kotlin:

fun main() {
var name: String? = null
println(name?.length)
}

18. Elvis Operator


Kotlin:

fun main() {
var name: String? = null
val length = name?.length ?: 0
println(length)
}

19. Data Class


Kotlin:

data class Car(val brand: String, val year: Int)

fun main() {
val car = Car("Toyota", 2020)
println(car)
}

20. Loop with Index


Kotlin:

fun main() {
val colors = listOf("Red", "Green", "Blue")
for ((index, color) in colors.withIndex()) {
println("Color at index $index is $color")
}
}
21. Lambda Function
Kotlin:

fun main() {
val square = { x: Int -> x * x }
println(square(5))
}

22. Higher-Order Function


Kotlin:

fun operate(a: Int, b: Int, op: (Int, Int) -> Int): Int {
return op(a, b)
}

fun main() {
val result = operate(3, 4) { x, y -> x + y }
println(result)
}

23. Filter a List


Kotlin:

fun main() {
val nums = listOf(1, 2, 3, 4, 5)
val even = nums.filter { it % 2 == 0 }
println(even)
}

24. Map a List


Kotlin:

fun main() {
val nums = listOf(1, 2, 3)
val doubled = nums.map { it * 2 }
println(doubled)
}
25. String Interpolation
Kotlin:

fun main() {
val name = "Tom"
val age = 30
println("My name is $name and I am $age years old.")
}

26. String Templates with Expressions


Kotlin:

fun main() {
val x = 10
val y = 5
println("Sum of $x and $y is ${x + y}")
}

27. Read-Only vs Mutable List


Kotlin:

fun main() {
val readOnly = listOf("a", "b")
val mutable = mutableListOf("x", "y")
mutable.add("z")
println(mutable)
}

28. Check Element in List


Kotlin:

fun main() {
val fruits = listOf("Apple", "Orange", "Banana")
if ("Apple" in fruits) {
println("Found Apple!")
}
}
29. Exception Handling
Kotlin:

fun main() {
try {
val result = 10 / 0
} catch (e: ArithmeticException) {
println("Error: ${e.message}")
}
}

30. Null Check with let


Kotlin:

fun main() {
val name: String? = "Alice"
name?.let {
println("Length is ${it.length}")
}
}

31. For Loop with Step


Kotlin:

fun main() {
for (i in 1..10 step 2) {
println(i)
}
}

32. For Loop in Reverse


Kotlin:

fun main() {
for (i in 5 downTo 1) {
println(i)
}
}
33. Break in Loop
Kotlin:

fun main() {
for (i in 1..5) {
if (i == 3) break
println(i)
}
}

34. Continue in Loop


Kotlin:

fun main() {
for (i in 1..5) {
if (i == 3) continue
println(i)
}
}

35. Check String Empty or Not


Kotlin:

fun main() {
val text = ""
if (text.isEmpty()) {
println("Empty string")
}
}

36. Compare Two Numbers


Kotlin:

fun main() {
val a = 10
val b = 20
val max = if (a > b) a else b
println("Max is $max")
}
37. Array Access by Index
Kotlin:

fun main() {
val nums = arrayOf(10, 20, 30)
println(nums[1])
}

38. Loop Through Map


Kotlin:

fun main() {
val map = mapOf("A" to 1, "B" to 2)
for ((key, value) in map) {
println("$key -> $value")
}
}

39. Default Parameters in Function


Kotlin:

fun greet(name: String = "Guest") {


println("Hello, $name")
}

fun main() {
greet()
greet("Bob")
}

40. Named Arguments


Kotlin:

fun greet(name: String, age: Int) {


println("Name: $name, Age: $age")
}

fun main() {
greet(age = 25, name = "Anna")
}
41. Range Check
Kotlin:

fun main() {
val number = 5
if (number in 1..10) {
println("Number is in range")
}
}

42. Function Returning Unit


Kotlin:

fun sayHello(): Unit {


println("Hello!")
}

fun main() {
sayHello()
}

43. Multiple Return Statements


Kotlin:

fun checkNumber(n: Int): String {


if (n > 0) return "Positive"
if (n < 0) return "Negative"
return "Zero"
}

fun main() {
println(checkNumber(0))
}

44. Chained Method Calls


Kotlin:

fun main() {
val text = "kotlin"
println(text.uppercase().reversed())
}
45. Function Inside Function
Kotlin:

fun outerFunction() {
fun innerFunction() {
println("Hello from inner function")
}
innerFunction()
}

fun main() {
outerFunction()
}

46. Function Expression Syntax


Kotlin:

fun square(x: Int) = x * x

fun main() {
println(square(4))
}

47. Array Size


Kotlin:

fun main() {
val arr = arrayOf(1, 2, 3)
println("Size: ${arr.size}")
}

48. String to Int Conversion


Kotlin:

fun main() {
val str = "123"
val num = str.toInt()
println(num + 1)
}
49. Safe String to Int Conversion
Kotlin:

fun main() {
val str = "abc"
val num = str.toIntOrNull()
println(num ?: "Invalid number")
}

50. Repeat Block


Kotlin:

fun main() {
repeat(3) {
println("Repeat $it")
}
}

51. Sealed Class


Kotlin:

sealed class Shape


class Circle(val radius: Double) : Shape()
class Square(val side: Double) : Shape()

fun main() {
val shape: Shape = Circle(2.0)
when (shape) {
is Circle -> println("Circle with radius ${shape.radius}")
is Square -> println("Square with side ${shape.side}")
}
}
52. Object Expression (Anonymous Object)
Kotlin:

fun main() {
val obj = object {
val x = 10
val y = 20
}
println("x = ${obj.x}, y = ${obj.y}")
}

53. Singleton using Object Keyword


Kotlin:

object Logger {
fun log(msg: String) {
println("Log: $msg")
}
}

fun main() {
Logger.log("Started App")
}

54. Extension Function


Kotlin:

fun String.reverse(): String {


return this.reversed()
}

fun main() {
println("hello".reverse())
}
55. Enum Class
Kotlin:

enum class Direction {


NORTH, SOUTH, EAST, WEST
}

fun main() {
val dir = Direction.NORTH
println(dir)
}

56. Use Enum in When Statement


Kotlin:

enum class Color { RED, GREEN, BLUE }

fun main() {
val color = Color.GREEN
when (color) {
Color.RED -> println("Red")
Color.GREEN -> println("Green")
Color.BLUE -> println("Blue")
}
}

57. Type Alias


Kotlin:

typealias UserMap = Map<String, String>

fun main() {
val user: UserMap = mapOf("name" to "Alice")
println(user)
}
58. Destructuring Declarations
Kotlin:

data class Point(val x: Int, val y: Int)

fun main() {
val (x, y) = Point(10, 20)
println("x = $x, y = $y")
}

59. Companion Object


Kotlin:

class MathUtil {
companion object {
fun square(x: Int): Int = x * x
}
}

fun main() {
println(MathUtil.square(6))
}

60. Simple Interface Implementation


Kotlin:

interface Animal {
fun speak()
}

class Dog : Animal {


override fun speak() {
println("Woof!")
}
}

fun main() {
val dog = Dog()
dog.speak()
}
61. Abstract Class
Kotlin:

abstract class Animal {


abstract fun sound()
}

class Cat : Animal() {


override fun sound() {
println("Meow")
}
}

fun main() {
val cat = Cat()
cat.sound()
}

62. Lateinit Variable


Kotlin:

class Person {

lateinit var name: String

private set // This makes the setter private

fun setName(newName: String) {

name = newName

fun main() {

val p = Person()

p.setName("Alice")

println(p.name)

}
63. Initialization Block
Kotlin:

class Book(val title: String) {


init {
println("Book titled \"$title\" is created.")
}
}

fun main() {
Book("Kotlin Basics")
}

64. Secondary Constructor


Kotlin:

class Person(val name: String) {


var age: Int = 0
constructor(name: String, age: Int) : this(name) {
this.age = age
}
}

fun main() {
val person = Person("Bob", 30)
println("${person.name}, ${person.age}")
}

65. Nested Class


Kotlin:

class Outer {
class Nested {
fun hello() = "Hello from nested class"
}
}

fun main() {
val nested = Outer.Nested()
println(nested.hello())
}
66. Inner Class
Kotlin:

class Outer {
private val text = "Outer text"
inner class Inner {
fun show() = text
}
}

fun main() {
val inner = Outer().Inner()
println(inner.show())
}

67. Generic Function


Kotlin:

fun <T> display(item: T) {


println(item)
}

fun main() {
display("Kotlin")
display(123)
}

68. Generic Class


Kotlin:

class Box<T>(val item: T) {


fun get(): T = item
}

fun main() {
val intBox = Box(100)
val strBox = Box("Hello")
println(intBox.get())
println(strBox.get())
}
69. Custom Getter
Kotlin:

class Circle(val radius: Double) {


val area: Double
get() = 3.14 * radius * radius
}

fun main() {
val c = Circle(3.0)
println("Area: ${c.area}")
}

70. Custom Setter


Kotlin:

class User {
var age: Int = 0
set(value) {
field = if (value >= 0) value else 0
}
}

fun main() {
val user = User()
user.age = -5
println("Age: ${user.age}")
}

71. String Equality


Kotlin:

fun main() {
val a = "hello"
val b = "hello"
println(a == b) // Structural equality
println(a === b) // Referential equality
}
72. Loop with Range Until
Kotlin:

fun main() {
for (i in 1 until 5) {
println(i)
}
}

73. Using Pair


Kotlin:

fun main() {
val pair = Pair("Alice", 25)
println("Name: ${pair.first}, Age: ${pair.second}")
}

74. Triple Example


Kotlin:

fun main() {
val triple = Triple("Tom", "Manager", 40)
println("Name: ${triple.first}, Job: ${triple.second}, Age:
${triple.third}")
}

75. Check Type with is


Kotlin:

fun checkType(x: Any) {


if (x is String) {
println("It's a String of length ${x.length}")
}
}

fun main() {
checkType("Kotlin")
}
76. Smart Cast
Kotlin:

fun describe(obj: Any) {


if (obj is String) {
println(obj.uppercase()) // Smart cast to String
}
}

fun main() {
describe("hello")
}

77. Type Casting with as


Kotlin:

fun main() {
val x: Any = "Kotlin"
val y = x as String
println(y.length)
}

78. Safe Casting with as?


Kotlin:

fun main() {
val x: Any = 123
val y: String? = x as? String
println(y) // Will print null instead of throwing an error
}

79. Loop Through Characters of String


Kotlin:

fun main() {
val word = "Kotlin"
for (ch in word) {
println(ch)
}
}
80. Sum of List
Kotlin:

fun main() {
val numbers = listOf(1, 2, 3, 4)
val sum = numbers.sum()
println("Sum: $sum")
}

81. Min and Max of List


Kotlin:

fun main() {
val numbers = listOf(5, 2, 9, 1)
println("Min: ${numbers.minOrNull()}, Max: ${numbers.maxOrNull()}")
}

82. Sort List


Kotlin:

fun main() {
val list = listOf(4, 2, 7, 1)
println(list.sorted())
}

83. Reverse List


Kotlin:

fun main() {
val list = listOf(1, 2, 3)
println(list.reversed())
}
84. Count Items in List
Kotlin:

fun main() {
val items = listOf("a", "b", "a", "c")
println(items.count { it == "a" })
}

85. All / Any Conditions


Kotlin:

fun main() {
val nums = listOf(2, 4, 6)
println(nums.all { it % 2 == 0 }) // true
println(nums.any { it > 5 }) // true
}

86. Check if List is Empty


Kotlin:

fun main() {
val list = emptyList<String>()
println(list.isEmpty())
}

87. Join List to String


Kotlin:

fun main() {
val list = listOf("a", "b", "c")
println(list.joinToString(", "))
}
88. Take and Drop
Kotlin:

fun main() {
val nums = listOf(1, 2, 3, 4, 5)
println(nums.take(3)) // [1, 2, 3]
println(nums.drop(2)) // [3, 4, 5]
}

89. Zipping Lists


Kotlin:

fun main() {
val a = listOf(1, 2, 3)
val b = listOf("a", "b", "c")
println(a.zip(b))
}

90. Unzipping Pairs


Kotlin:

fun main() {
val zipped = listOf(1 to "a", 2 to "b")
val (nums, letters) = zipped.unzip()
println(nums)
println(letters)
}

91. Chunked List


Kotlin:

fun main() {
val list = (1..10).toList()
println(list.chunked(3))
}
92. Windowed List
Kotlin:

fun main() {
val list = listOf(1, 2, 3, 4, 5)
println(list.windowed(3))
}

93. Flatten List


Kotlin:

fun main() {
val list = listOf(listOf(1, 2), listOf(3, 4))
println(list.flatten())
}

94. FlatMap
Kotlin:

fun main() {
val list = listOf("abc", "de")
val chars = list.flatMap { it.toList() }
println(chars)
}

95. Remove Duplicates


Kotlin:

fun main() {
val list = listOf(1, 2, 2, 3)
println(list.distinct())
}
96. Group By
Kotlin:

fun main() {
val list = listOf("one", "two", "three", "four")
val grouped = list.groupBy { it.length }
println(grouped)
}

97. Associate By
Kotlin:

fun main() {
val people = listOf("Alice", "Bob", "Charlie")
val map = people.associateBy { it.first() }
println(map)
}

98. Measure Execution Time


Kotlin:

import kotlin.system.measureTimeMillis

fun main() {
val time = measureTimeMillis {
Thread.sleep(200)
}
println("Time: $time ms")
}

99. Repeat with Index


Kotlin:

fun main() {
repeat(3) {
println("Index $it")
}
}
100. Create Range and Convert to List
Kotlin:

fun main() {
val range = (1..5).toList()
println(range)
}

Email:
[email protected]

Blogger:
https://souhaillaghchim-dev.blogspot.com/

You might also like