这个问题在这里已经有了答案:
Why is Nil required at the end of a list built using the cons operator
(3 个回答)
5年前关闭。
我有一个关于 List 的基本问题
当我尝试使用 cons 运算符创建列表时出现以下错误
scala> val someList = 1::2
<console>:10: error: value :: is not a member of Int
val someList = 1::2
^
但是如果你看看下面,只要我在末尾添加 Nil 它就可以工作..
scala> val someList = 1::2::Nil
someList: List[Int] = List(1, 2)
我想知道为什么在我们创建列表时最后至少需要一次 Nil
Nil 是数据类型吗?还是空元素?
最佳答案
正是因为这个原因。
value :: is not a member of Int
在 Scala 中,操作符实际上是对象上的函数。在这种情况下,
::
是 Nil
上的一个函数对象,它实际上是一个空列表对象。scala> Nil
res0: scala.collection.immutable.Nil.type = List()
当您这样做时
1::2
, Scala 查找名为 ::
的函数在 2
它没有找到。这就是为什么它因该错误而失败。注:在 Scala 中,如果运算符的最后一个字符不是冒号,则在第一个操作数上调用该运算符。例如,
1 + 2
基本上是 1.+(2)
.但是,如果最后一个字符是冒号,则在右侧操作数上调用运算符。所以在这种情况下,1 :: Nil
实际上是 Nil.::(1)
.由于,::
返回另一个列表对象,你可以链接它,就像这样 1 :: 2 :: Nil
实际上,Nil.::(2).::(1)
.
关于list - 为什么我们在 Scala 中创建 List 时需要 Nil?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37741565/