← Back to Scala Course | Chapter 6: Collections Basics | Lesson 1 of 8

List के Basics

एक List items की एक chain है जिसे एक बार बनने के बाद बदला नहीं जा सकता, जैसे जुड़े हुए डिब्बों की एक train। अलग list पाने के लिए आप एक नई बनाते हैं।

In this page:

  1. List Basics
Syntax
scala
val list = List(value1, value2, value3)
val newList = value0 :: list
val joined = list1 ::: list2

List Basics

एक Scala List एक immutable, singly-linked sequence है, जो List(1, 2, 3) से बनाई जाती है। immutable होने के कारण, कोई element जोड़ने जैसे operations original को modify करने के बजाय एक *नई* list return करते हैं।

:: ("cons") किसी list के सामने efficiently एक element जोड़ता है, और Nil खाली list को represent करता है।

Note: 1 :: 2 :: 3 :: Nil, cons का उपयोग करके List(1, 2, 3) बनाने का एक समान, ज़्यादा explicit तरीका है।

उदाहरण: List Basics

markup
object Main extends App {
  val numbers = List(1, 2, 3, 4)
  val withZero = 0 :: numbers

  println(numbers)
  println(withZero)
  println(numbers.length)
}
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. numbers(0) = 5 से किसी list को बदलने की कोशिश करना, जबकि एक List immutable है और इसमें कोई update नहीं है।
  2. यह उम्मीद करना कि numbers :+ 5 या 0 :: numbers numbers को modify करेंगे, जबकि वे एक नई list return करते हैं।
  3. लंबी lists के लिए loop में list(i) का उपयोग करना, जो धीमा है क्योंकि एक List एक linked list है जिसकी linear access होती है।
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 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.