Article Directory
In Scala, Nil
is a special object representing an empty list. It's List
an instance of type , but it's an empty list with no elements. In Scala's standard library, Nil
is a singleton object that represents the only instance of an empty list.
Nil
Inherits from List[Nothing]
, so it can be List
used as any type of , such as List[Int]
, List[String]
etc. Since lists in Scala are immutable, Nil
the empty list represented by is also immutable. Once created, elements cannot be added or removed.
Nil
Can 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 Nil
examples of creating an empty list and building a new list using:
1. Nil
Create an empty list using
val emptyList: List[Int] = Nil
2. Use to Nil
add elements at the beginning of the list
val myList: List[Int] = 1 :: 2 :: 3 :: Nil
In the above example, we created Nil
an empty list with emptyList
, and then Nil
built a list containing 1, 2, and 3 with Add elements at the beginning of the list myList
.
Since Nil
is a singleton object, when comparing whether the list is empty, usually use Nil
to 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 myList
is an empty list, output "List is empty." Otherwise output "List is not empty.".
Summary: Nil
It is a special object representing an empty list in Scala, and it is List
an 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, Nil
the represented empty list is also immutable.