Fields और Methods
Fields वे facts हैं जो एक object याद रखता है और methods वे चीज़ें हैं जो वह कर सकता है, जैसे एक dog जिसका एक नाम हो और जो bark कर सके। constructor inputs में val या var जोड़ने से वे fields बन जाते हैं।
In this page:
Syntax
class ClassName(val field1: Type, var field2: Type) {
def method_name(param: Type): ReturnType = {
// body
}
}
Fields and Methods
किसी constructor parameter से पहले val या var जोड़ना, जैसे class Point(val x: Int, val y: Int), उसे instances पर एक public, read-only (या mutable, var के लिए) field के रूप में उजागर करता है।
Methods को class body के अंदर def से define किया जाता है और वे इन fields को सीधे access कर सकते हैं। val/var के बिना, एक constructor parameter सिर्फ class body के अंदर उपयोग होता है, बाहर से access नहीं होता।
Note:
val/var के बिना एक constructor parameter class body के लिए private होता है -- इसे public field के रूप में उजागर करने के लिए val जोड़ें।उदाहरण: Fields and Methods
class Rectangle(val width: Int, val height: Int) {
def area(): Int = width * height
}
object Main extends App {
val rect = new Rectangle(4, 5)
println(rect.width)
println(rect.area())
}
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. #}
आम गलतियां
class Point(x: Int)declare करना औरp.xaccess करना, जो fail हो जाता है क्योंकिvalके बिना parameter एक public field नहीं है।def area = width * height()लिखना जिसमें parentheses styles मिल जाती हैं, जबकि()से defined method को()से call किया जाता है।rect.width = 10जैसे किसीvalfield को assign करने की कोशिश करना, जबकि reassignable होने के लिए इसेvarचाहिए।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: