fun greet(name: String): String {
return "Hello, $name!"
}
fun sum(a: Int, b: Int) = a + b
fun printSum(a: Int, b: Int): Unit {
println(a + b)
}
fun printSum(a: Int, b: Int) {
println(a + b)
}
fun greet(name: String = "Guest", greeting: String = "Hello") {
println("$greeting, $name!")
}
greet()
greet("Alice")
greet("Bob", "Hi")
fun createUser(name: String, age: Int, email: String) {
}
createUser(
name = "Alice",
age = 25,
email = "alice@example.com"
)
createUser("Bob", age = 30, email = "bob@example.com")
fun sum(vararg numbers: Int): Int {
return numbers.sum()
}
sum(1, 2, 3, 4, 5)
val nums = intArrayOf(1, 2, 3)
sum(*nums)
val operation: (Int, Int) -> Int = { a, b -> a + b }
val result = operation(5, 3)
val nullable: (Int) -> Int? = { if (it > 0) it else null }
fun calculate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}
val sum = calculate(5, 3) { x, y -> x + y }
val product = calculate(5, 3) { x, y -> x * y }
fun makeMultiplier(factor: Int): (Int) -> Int {
return { number -> number * factor }
}
val double = makeMultiplier(2)
println(double(5))
val sum = { a: Int, b: Int -> a + b }
val numbers = listOf(1, 2, 3, 4, 5)
val doubled = numbers.map { it * 2 }
val result = numbers.filter {
val isEven = it % 2 == 0
isEven
}
numbers.forEach { println(it) }
val map = mapOf("a" to 1, "b" to 2)
map.forEach { _, value -> println(value) }
val sum = fun(a: Int, b: Int): Int {
return a + b
}
val multiply = fun(a: Int, b: Int) = a * b
inline fun measureTime(block: () -> Unit) {
val start = System.currentTimeMillis()
block()
val end = System.currentTimeMillis()
println("Time: ${end - start}ms")
}
measureTime {
}
fun String.removeSpaces(): String {
return this.replace(" ", "")
}
val text = "Hello World"
println(text.removeSpaces())
fun String?.isNullOrEmpty(): Boolean {
return this == null || this.isEmpty()
}
infix fun Int.times(str: String) = str.repeat(this)
val result = 3 times "Hello"
tailrec fun factorial(n: Int, acc: Int = 1): Int {
return if (n <= 1) acc
else factorial(n - 1, n * acc)
}
println(factorial(5))
fun processUser(user: User) {
fun validate(value: String, fieldName: String) {
if (value.isEmpty()) {
throw IllegalArgumentException("$fieldName is empty")
}
}
validate(user.name, "Name")
validate(user.email, "Email")
}