Type Classes के Basics
एक type class types को बिना बदले एक नई ability जोड़ने का pattern है, जैसे कई अलग-अलग जानवरों को एक जैसा trick card देना। फिर code किसी भी ऐसे type के लिए काम करता है जिसके पास वह card हो।
In this page:
Syntax
trait TypeClass[T] {
def operation(value: T): ReturnType
}
implicit val instance: TypeClass[Type] = new TypeClass[Type] {
def operation(value: Type): ReturnType = expression
}
def function_name[T](value: T)(implicit tc: TypeClass[T]) = tc.operation(value)
Type Classes Basics
एक type class एक pattern है (कोई खास keyword नहीं) जहां एक trait कोई capability define करता है, जैसे Show[T], और अलग implicit instances specific types के लिए वह capability प्रदान करते हैं, बिना उन types की original definitions बदले।
फिर एक generic function किसी भी type के साथ काम करने के लिए उस type class का एक implicit instance parameter के रूप में मांगता है जिसके पास एक हो। यह हर type को सीधे एक shared interface implement करने की ज़रूरत का Scala का लचीला विकल्प है।
Note:
Type classes आपको मौजूदा types (यहां तक कि जो आप owner नहीं हैं, जैसे Int) में बिना inheritance या source बदले नया behavior जोड़ने देते हैं।
उदाहरण: Type Classes Basics
trait Show[T] {
def show(value: T): String
}
object Show {
implicit val intShow: Show[Int] = (value: Int) => s"Int($value)"
implicit val stringShow: Show[String] = (value: String) => s"Str($value)"
}
object Main extends App {
def display[T](value: T)(implicit s: Show[T]): Unit = {
println(s.show(value))
}
import Show._
display(42)
display("hello")
}
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. #}
आम गलतियां
- implicit instance को scope में रखना भूल जाना, जिससे call
could not find implicit value for parameterके साथ fail हो जाती है। - instance को गलत type के लिए define करना, जैसे
Show[Long]जब callIntउपयोग करती है। - किसी type class को inheritance के साथ confuse करना, जबकि एक type class मौजूदा types में बिना बदले behavior जोड़ता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: