Traits को Mix करना
parents के विपरीत, एक class एक साथ कई traits mix in कर सकती है, जैसे कोई student जो choir, chess club, और soccer team सभी में शामिल हो। हर trait अपनी खुद की abilities जोड़ता है।
In this page:
Syntax
class ClassName extends FirstTrait with SecondTrait with ThirdTrait {
// body
}
val obj = new ClassName with ExtraTrait
Mixing in Traits
Classes के विपरीत, एक Scala class extends Trait1 with Trait2 with Trait3 का उपयोग करके एक साथ कई traits mix in कर सकती है, और कई स्वतंत्र sources से behavior combine कर सकती है।
यह Scala का multiple inheritance का सुरक्षित विकल्प है, जिसे अस्पष्ट conflicts के बजाय एक अच्छी तरह परिभाषित linearization order से हल किया जाता है। जब traits एक ही method को override करते हैं तो order मायने रखता है -- chain में सबसे दाहिनी ओर वाले trait का version आमतौर पर प्राथमिकता लेता है।
Note:
पहले trait के अलावा अतिरिक्त traits mix in करने के लिए
with का उपयोग करें, जैसे class C extends TraitA with TraitB with TraitC।उदाहरण: Mixing in Traits
trait Flyable {
def fly(): Unit = println("Flying")
}
trait Swimmable {
def swim(): Unit = println("Swimming")
}
class Duck extends Flyable with Swimmable
object Main extends App {
val duck = new Duck()
duck.fly()
duck.swim()
}
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. #}
आम गलतियां
extends Flyable with Swimmableके बजायextends Flyable extends Swimmableलिखना।- अलग-अलग bodies वाले एक जैसे method को define करने वाले traits को मिलाना, जिससे एक conflict होता है जिसके लिए
overrideचाहिए। - यह उम्मीद करना कि mix in किए गए traits का order irrelevant है, जबकि order यह तय करता है कि कौन सा
overrideपहले call होता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: