← Back to Kotlin Course | Chapter 9: Lambdas & Higher-Order Functions | Lesson 2 of 6

Function Types क्या हैं

एक function type किसी function की shape describe करता है -- यह क्या लेता है और क्या वापस देता है -- ताकि आप किसी function को किसी और value की तरह एक variable में store कर सकें।
Syntax
kotlin
val name: (ParamType) -> ReturnType = { p -> expression }

fun functionName(action: (ParamType) -> ReturnType) {
    action(value)
}

fun other(task: () -> Unit) { task() }

Declaring a Function Type

एक function type किसी function की shape describe करता है: parentheses में parameter types, एक arrow, फिर return type -- उदाहरण के लिए (Int, Int) -> Int दो Ints लेने और एक लौटाने वाले function के लिए।

उदाहरण: Declaring a Function Type

markup
// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `multiply` (a `(Int, Int) -> Int`), set to `{ a, b -> a * b }`
    val multiply: (Int, Int) -> Int = { a, b -> a * b }
    // Print "Product: ${multiply(6, 7)}" to the console, with a trailing newline
    println("Product: ${multiply(6, 7)}")
}

Function Types as Parameters

कोई function किसी दूसरे function को एक parameter के रूप में accept कर सकता है उस parameter को एक function type से declare करके, behavior को किसी भी दूसरी value की तरह पास होने देते हुए।

उदाहरण: Function Types as Parameters

markup
// Define the function `applyOperation` taking `a`, `b`, `operation` and returning an Int
fun applyOperation(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
    // Return `operation(a, b)` from this function
    return operation(a, b)
}

// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `result`, set to `applyOperation(4, 5) { x, y -> x + y }`
    val result = applyOperation(4, 5) { x, y -> x + y }
    // Print "Result: $result" to the console, with a trailing newline
    println("Result: $result")
}

Function Types That Return Unit

() -> Unit बिना parameters वाले एक ऐसे function को describe करता है जो एक action करता है लेकिन कोई मायने रखने वाली value produce नहीं करता, दूसरी languages में void method जैसा।

उदाहरण: Function Types That Return Unit

markup
// Define the function `runTask` taking `task`
fun runTask(task: () -> Unit) {
    // Print "Starting task..." to the console, with a trailing newline
    println("Starting task...")
    task()
    // Print "Task finished" to the console, with a trailing newline
    println("Task finished")
}

// Entry point: execution of the program starts here
fun main() {
    runTask { println("Doing work") }
}

Storing Functions in Variables

चूंकि Kotlin में functions values हैं, एक variable एक function type का उपयोग करके किसी एक का reference रख सकता है, और उस variable को बाद में बिल्कुल एक regular function की तरह call किया जा सकता है।

उदाहरण: Storing Functions in Variables

markup
// Entry point: execution of the program starts here
fun main() {
    val operations = mapOf<String, (Int, Int) -> Int>(
        "add" to { a, b -> a + b },
        "subtract" to { a, b -> a - b }
    )
    // Print "5 + 3 = ${operations["add"]!!(5, 3)}" to the console, with a trailing newline
    println("5 + 3 = ${operations["add"]!!(5, 3)}")
    // Print "5 - 3 = ${operations["subtract"]!!(5, 3)}" to the console, with a trailing newline
    println("5 - 3 = ${operations["subtract"]!!(5, 3)}")
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. किसी function type में parameter types के चारों ओर parentheses भूल जाना, (Int) -> Int के बजाय Int -> Int लिखते हुए।
  2. एक nullable function type (() -> Unit)? को एक nullable type return करने वाले function () -> Unit? के साथ confuse करना; parentheses की placement मायने रखती है।
  3. जहां एक function type की उम्मीद हो वहां एक lambda या function reference के बजाय एक साधारण value पास करने की कोशिश करना।
चैप्टर सारांश
  • एक function type (ParamTypes) -> ReturnType के रूप में लिखा जाता है, जैसे (Int, Int) -> Int।
  • Variables, parameters, और properties सभी को एक function type से declare किया जा सकता है और एक lambda या function reference रख सकते हैं।
  • () -> Unit एक ऐसे function को describe करता है जो कोई parameters नहीं लेता और कुछ मायने रखने वाला return नहीं करता।
  • Function types behavior को खुद data के रूप में पास करना संभव बनाते हैं, जो higher-order functions का केंद्रीय हिस्सा है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.