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

Trait के Basics

एक trait abilities का एक बंडल है जिसे कोई class अपना सकती है, जैसे एक skill card जिस पर लिखा हो 'तैर सकता है'। यह promises और तैयार actions दोनों रख सकता है।

In this page:

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

markup
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()
}
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. new Greetable से किसी trait को instantiate करने की कोशिश करना, जबकि इसे सिर्फ किसी class या anonymous subclass के ज़रिए बनाया जा सकता है।
  2. abstract member name को define करना भूल जाना, जिससे class compile नहीं होती।
  3. दूसरे trait के लिए extends का उपयोग करना, जबकि पहला extends उपयोग करता है और बाकी को with चाहिए।
🔒

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.