Open ezrohir opened 1 year ago
fun functionName(parameterName: DataType): ReturnType {
//function body
}
fun greetUser(name: String): String {
return "Hello ${name}!"
}
fun greetUser(name: String = "World"): String {
return "Hello ${name}!"
}
greetUser() //returns Hello World!
val square = { a:Int ->
a * a
}
println(square(4)) //16
var multiple: (Int) -> Int = { it * it }
println(multiple(4)) //16
multiple = {it * it * it} //don't need '->'
println(multiple(2)) //8
// 1
val lambda1: (String) -> Unit = { name: String -> println("Hello, $name") }
// 2
val lambda2: (String) -> Unit = { name -> println("Hello, $name") }
// 3
val lambda3: (String) -> Unit = { println("Hello, $it") }
// 4
val lambda4: (String) -> Unit = { println("Hello, World!") }
// 5
val lambda5: (Int, Int) -> Int = { x, y ->
print(x)
print(y)
x + y
}
// 6
val lambda6 = {x: Int, y: Int -> x + y }
// kotlin Nullable Type
var authToken: String? = "some long string"
authToken = null
// Swift Optional Type
var authToken: String? = "some long string"
authToken = nil
Elvis Operator ?:
var id: Int? = null
val userId = id ?: -1 //userId is -1
fun readyForParade (participant : Bandmember) : Boolean {
val trombonePlayer = participant as? Bandmember ?: return false
return trombonePlayer. practiceTime > 6000
}
Kotlin-when
val x = 3
when (x) {
1 -> println("x == 1")
2 -> println("x == 2")
else -> {
print("x is neither 1 nor 2")
}
}
Swift-switch
let x = 3
switch x {
case 1:
print("x == 1")
case 2:
print("x == 2")
default:
print("x is neither 1 nor 2")
}
Kotlin - Extension
fun Int.square(): Int {
return this * this
}
println(5.square()) //prints 25
Swift - Extension
extension Int {
func square() -> Int {
return self * self
}
}
print(5.square()) //prints 25
// Kotlin — Interface
interface Animal {
var canFly: Boolean
fun eat()
fun makeSound()
}
// Swift - Protocol
protocol Animal {
var canFly: Bool {get}
func eat()
func makeSound()
}
// Kotlin
interface Animal {
val canFly: Boolean
get() = true
}
// Swift
protocol Animal {
var canFly: Bool {get}
}
extension Animal {
var canFly: Bool {
return false
}
}
Dictionaries / Maps