← Back to Scala Course | Chapter 8: Inheritance & Traits | Lesson 5 of 7

Traits को Mix करना

parents के विपरीत, एक class एक साथ कई traits mix in कर सकती है, जैसे कोई student जो choir, chess club, और soccer team सभी में शामिल हो। हर trait अपनी खुद की abilities जोड़ता है।

In this page:

  1. Mixing in Traits
Syntax
scala
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

markup
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()
}
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. extends Flyable with Swimmable के बजाय extends Flyable extends Swimmable लिखना।
  2. अलग-अलग bodies वाले एक जैसे method को define करने वाले traits को मिलाना, जिससे एक conflict होता है जिसके लिए override चाहिए।
  3. यह उम्मीद करना कि mix in किए गए traits का order irrelevant है, जबकि order यह तय करता है कि कौन सा override पहले 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.