[Scala collection] 14, Nil empty list object

insert image description here

In Scala, Nilis a special object representing an empty list. It's Listan instance of type , but it's an empty list with no elements. In Scala's standard library, Nilis a singleton object that represents the only instance of an empty list.

NilInherits from List[Nothing], so it can be Listused as any type of , such as List[Int], List[String]etc. Since lists in Scala are immutable, Nilthe empty list represented by is also immutable. Once created, elements cannot be added or removed.

NilCan be used to create an empty list, or to add elements to the beginning of another list to build a new list.

1. Nil

Here are some Nilexamples of creating an empty list and building a new list using:

1. NilCreate an empty list using

val emptyList: List[Int] = Nil

2. Use to Niladd elements at the beginning of the list

val myList: List[Int] = 1 :: 2 :: 3 :: Nil

In the above example, we created Nilan empty list with emptyList, and then Nilbuilt a list containing 1, 2, and 3 with Add elements at the beginning of the list myList.

Since Nilis a singleton object, when comparing whether the list is empty, usually use Nilto judge, for example:

val myList: List[Int] = List(1, 2, 3)

if (myList == Nil) {
    
    
  println("List is empty.")
} else {
    
    
  println("List is not empty.")
}

In the above example, if myListis an empty list, output "List is empty." Otherwise output "List is not empty.".

Summary: NilIt is a special object representing an empty list in Scala, and it is Listan instance of the type. It can be used to create empty lists, or it can be used to add elements to the beginning of other lists to build new lists. Since lists are immutable, Nilthe represented empty list is also immutable.

おすすめ

転載: blog.csdn.net/m0_47256162/article/details/132159729