Files
kotlin-for-java-developers/src/Functions.kt

35 lines
903 B
Kotlin
Raw Normal View History

// Specify the name to use when calling from another language
@file:JvmName("fun")
fun main() {
print(max(2, 3))
println(
// Named arguments are optional
listOf("a", "b", "c").joinToString(
separator = "",
prefix = "(",
postfix = ")"
)
)
// Using default value
println(repeatString("*"))
println(repeatString("*", 2))
// Flip the arguments by using named arguments
println(repeatString(times = 5, s = "*"))
}
// Top-level function
fun max(a: Int, b: Int): Int = if (a > b) a else b
// Unit return type
fun print(value: Int) = println("Max is $value")
// Times has a default value
fun repeatString(s: String, times: Int = 10): String = s.repeat(times)
// Generates 4 overloaded functions for the JVM. Not needed when only using Kotlin
@JvmOverloads
fun sum(a: Int = 0, b: Int = 0, c: Int = 0) = a + b + c