← Back to Scala Course | Chapter 5: Functions | Lesson 1 of 7

Function के Basics

एक function एक नाम वाली recipe है जिसे आप एक बार लिखते हैं और जब चाहें उपयोग करते हैं। Scala में आप def लिखते हैं, उसे एक नाम देते हैं, और steps describe करते हैं।

In this page:

  1. Function Basics
Syntax
scala
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

markup
object Main extends App {
  def greet(): Unit = {
    println("Hello from a function!")
  }

  greet()
  greet()
}
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. def greet(): Unit = { ... } में = sign भूल जाना, जो एक अलग syntax या error बना देता है।
  2. greet को () के बिना लिखना जबकि इसे () के साथ define किया गया था, जो Scala 3 में warning या error दे सकता है।
  3. किसी 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:

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.