Reputation: 848
In Scala, Nil is actually an object which returns an empty List. When I type, Nil, it prints the following.
res24: scala.collection.immutable.Nil.type = List()
res24 is the variable whose type is scala.collection.immutable.Nil.type
. I don't quite understand the last piece 'type'. Where this is located ?
Another question is: Nil returns an empty list. How can we write an object which returns something? I tried below; it does not return the integer value what I expected.
object Sample { 123 }
val x = Sample
x: Sample.type = Sample$@36fe7b03
Thanks in advance!
Upvotes: 2
Views: 179
Reputation: 149538
I don't quite understand the last piece 'type'. Where this is located ?
This is what Scala refers to as the "Singleton Type". Nil
and Sample
share the common property of being objects in Scala which entails they are classes with a single instance (given that it is a top level declaration, and not nested inside a class
, inside a given package scope). It part of the type definition, but it isn't visible in the declaration site. For more on the uses of the singleton type see What is a Singleton Type exactly?
How can we write an object which returns something?
Writing an object
that returns something is similar to asking "Can I create a class that returns a value when instantiated?". object
are singletons and can have methods on them that returns values:
object Bar {
def x(): Int = 42
}
def main(args: Array[String]): Unit = print(Bar.x())
Which yields 42
.
Still I am not clear how the singleton object Nil, returning an empty list
If we can simplify and mimic the List[A]
definition, we'll see that:
sealed trait List[+A]
case class ::(head: A, tail: List[A]) extends List[A]
case object Nil extends List[Nothing]
What we have here is an Algebraic Data Type (ADT), more specifically a Sum Type, which is a type that's composed of multiple possible values. Here, a List[A]
can be either a ::
, or Nil
, and in our case it represents the empty list case.
Upvotes: 4
Reputation: 7845
In Scala, Nil is actually an object which returns an empty List.
No, Nil is an object that represents the empty list (by extending from List[Nothing]). See https://alvinalexander.com/scala/what-is-difference-between-nil-empty-list-in-scala/
Upvotes: 1