기본 적으로 자바와 동일하나 타입을 반드시 지정해야 함(자바에서는 필요 없음)
fun calculate(first: Int = 1, second: Int, message: String, multipleOf: Int) {
for (i in first..second) {
if (i % multipleOf == 0) println("$multipleOf $message $i")
}
}
val cal: (Int, Int, String, Int) -> Unit = { a, b, c, d ->
for (i in a..b)
if (i % d == 0) println("$d $c $i")
}
fun calCatAge(age: Int): Int = age * 7
val calCatAgeLambda: (Int) -> Int = {
it * 7 }
fun checkAge(catAge: Int): Boolean = catAge >= 40
val checkAgeLambda: (Int) -> Boolean = { a -> a > 33 }
fun sum(a: Int, b: Int): Int {
return a + b
}
val add: (Int, Int) -> Int = { a, b -> a + b }
//val lambdaName : Type = { parameter -> body }
Trailing Lambda
Compos에서 많이 사용하는 방식으로 람다를 생성시에 마지막에 함수(람다)를 파라미터로 지정하면 사용 시에 이 람다를 {}를 사용해서 지정가능 한 방식... 좀 혼란스러움
fun main() {
enhancedMessage("안녕 하세요"){
print(it)
add(33, 22)
}
}
//Trailing Lambda
fun enhancedMessage(
message: String,
funAsParameter: (String) -> Int
) {
println("$message : ${funAsParameter("trailing lambda input -> ")}")
}
fun main() {
val fahrenheit : (Double) -> Double = { celsius ->
celsius*(9.0/5.0) + 32 }
val celsius : (Double) -> Double = { kelvin ->
kelvin - 273.15 }
val kelvin : (Double) -> Double = {fahrenheit ->
(fahrenheit -32)*(5.0/9.0) + 273.15 }
printFinalTemperature(27.0, "celsius", "fahrenheit", fahrenheit)
printFinalTemperature(350.0, "kelvin", "celsius", celsius)
printFinalTemperature(10.0, "fahrenheit", "kelvin", kelvin)
}
fun printFinalTemperature(
initialMeasurement: Double,
initialUnit: String,
finalUnit: String,
conversionFormula: (Double) -> Double
) {
val finalMeasurement = String.format("%.2f", conversionFormula(initialMeasurement))
// two decimal places
println("$initialMeasurement degrees $initialUnit is $finalMeasurement degrees $finalUnit.")
}
'kotlin' 카테고리의 다른 글
Kotlin Collection Functions Cheat Sheet (0) | 2023.03.27 |
---|---|
kotlin 범위 지정 함수 : run/let, apply/also, with (0) | 2023.03.26 |
kotlin Array (0) | 2023.02.07 |
kotlin Cast - 형변환 (0) | 2023.02.07 |
kotlin collection (0) | 2023.02.07 |