Trait के Basics
एक trait abilities का एक बंडल है जिसे कोई class अपना सकती है, जैसे एक skill card जिस पर लिखा हो 'तैर सकता है'। यह promises और तैयार actions दोनों रख सकता है।
In this page:
Syntax
trait TraitName {
def abstractMethod(): ReturnType
def concreteMethod(): ReturnType = expression
}
class ClassName extends TraitName {
def abstractMethod(): ReturnType = expression
}
Trait Basics
एक trait किसी interface जैसा है लेकिन यह सिर्फ abstract signatures नहीं, concrete method implementations और fields भी प्रदान कर सकता है।
Traits constructor parameters नहीं ले सकते (Scala 3 से पहले), abstract classes के विपरीत। Traits Scala का मुख्य तरीका है जिससे अलग-अलग classes के बीच reusable behavior share किया जाता है।
Note:
किसी class के विपरीत, एक trait Scala 2 में constructor parameters नहीं ले सकता -- ज़रूरी configuration को abstract members के रूप में रखें।
उदाहरण: Trait Basics
trait Greetable {
def name: String
def greet(): Unit = {
println(s"Hello, I'm $name")
}
}
class Person(val name: String) extends Greetable
object Main extends App {
val p = new Person("Alice")
p.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. #}
आम गलतियां
new Greetableसे किसी trait को instantiate करने की कोशिश करना, जबकि इसे सिर्फ किसी class या anonymous subclass के ज़रिए बनाया जा सकता है।- abstract member
nameको define करना भूल जाना, जिससे class compile नहीं होती। - दूसरे trait के लिए
extendsका उपयोग करना, जबकि पहलाextendsउपयोग करता है और बाकी कोwithचाहिए।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: