Function के Basics
एक function एक नाम वाली recipe है जिसे आप एक बार लिखते हैं और जब चाहें उपयोग करते हैं। Scala में आप def लिखते हैं, उसे एक नाम देते हैं, और steps describe करते हैं।
In this page:
Syntax
def function_name(param: Type): ReturnType = {
// body
result
}
Function Basics
एक Scala function (या method, जब class/object के अंदर define हो) को def name(params): ReturnType = body से declare किया जाता है।
जब body एक single expression हो, = sign सीधे उसकी value को return value के रूप में assign कर देता है, बिना braces या return keyword की ज़रूरत के। Functions को नाम से call किया जाता है, बिल्कुल किसी built-in operation की तरह।
Note:
single-expression function body के लिए, braces optional हैं:
def square(n: Int): Int = n * n एक ही line में पूरा है।उदाहरण: Function Basics
object Main extends App {
def greet(): Unit = {
println("Hello from a function!")
}
greet()
greet()
}
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
def greet(): Unit = { ... }में=sign भूल जाना, जो एक अलग syntax या error बना देता है।greetको()के बिना लिखना जबकि इसे()के साथ define किया गया था, जो Scala 3 में warning या error दे सकता है।- किसी
objectके अंदर function define करना और उसे object बनाने से पहले call करना, जबकि किसीobjectपर methods को बाहर सेMain.greet()के रूप में call किया जाता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: