为什么在Scala中创建List时我们需要Nil? [英] Why do we need Nil while creating List in scala?

查看:388
本文介绍了为什么在Scala中创建List时我们需要Nil?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在列表上有一个基本问题

I have one basic question on List

当我尝试使用cons运算符创建列表时,出现以下错误

I am getting the below error when I tried to create a List with cons operator

scala> val someList = 1::2
<console>:10: error: value :: is not a member of Int
   val someList = 1::2
                   ^

但是,如果您查看下面的内容,那么只要我最后添加Nil即可.

But if you look at below, as soon as I add Nil at end it works..

    scala> val someList = 1::2::Nil
    someList: List[Int] = List(1, 2)

我想知道为什么为什么在创建列表时至少需要一次Nil

I would like to know why is it Nil is needed atleast once at the end when we create a list

Nil是否为dataType?还是空元素?

Is Nil a dataType? or empty element?

推荐答案

正是因为这个原因.

value ::不是Int的成员

value :: is not a member of Int

在Scala中,运算符实际上是对象上的函数.在这种情况下,::Nil对象上的一个函数,该对象实际上是一个空列表对象.

In Scala, the operators are actually functions on objects. In this case, :: is a function on Nil object, which is actually an Empty list object.

scala> Nil
res0: scala.collection.immutable.Nil.type = List()

当您执行1::2时,Scala在2上查找名为::的函数,但找不到该函数.这就是为什么它失败并显示该错误.

When you do 1::2, Scala looks for the function named :: on 2 and it doesn't find that. That is why it fails with that error.

注意:在Scala中,如果运算符的最后一个字符不是冒号,则会在第一个操作数上调用该运算符.例如,1 + 2基本上是1.+(2).但是,如果最后一个字符是冒号,则会在右侧操作数上调用运算符.因此,在这种情况下,1 :: Nil实际上是Nil.::(1).由于::返回另一个列表对象,因此可以将其链接起来,就像1 :: 2 :: Nil实际上是Nil.::(2).::(1).

Note: In Scala, if the last character of the operator is not colon, then the operator is invoked on the first operand. For example, 1 + 2 is basically 1.+(2). But, if the last character is colon, the the operator is invoked on the right hand side operand. So in this case, 1 :: Nil is actually Nil.::(1). Since, the :: returns another list object, you can chain it, like this 1 :: 2 :: Nil is actually, Nil.::(2).::(1).

这篇关于为什么在Scala中创建List时我们需要Nil?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆