2014-04-05 36 views
2

我正在学习Scala(编程Scala,第2版,Odersky)。为什么Nil需要在使用cons运算符构建的列表末尾

当使用利弊运营商,我们必须写建立一个列表:

val l = 1 :: 2 :: 3 :: 4 :: Nil 

为什么我们需要一个无在结束了吗?为什么不能编译器明白,4是最后一个元素,所以只写这个:

val l = 1 :: 2 :: 3 :: 4 

回答

8

::签名大致是:

case class ::[E](hd: E, tl: List[E]) extends List[E] 

// which generates this automatically: 

object :: { 
    def apply[E](hd: E, tl: List[E]): ::[E] 
} 

Nil签名大致是:

object Nil extends List[Nothing] 

如您所见,::需要一个元素和一个列表。 4不是一个列表,而Nil是。

+1

所以必须建立开始4 ::无列表,3 ::(4 ::无)等? –

+2

正确。以冒号(:)开头的操作符在Scala中是正确的关联,基本上支持这个用例。 –

+1

我认为这个答案在提及'::'case类时很混乱。这是与问题相关的'::'方法。 –

2

其实,你可以让它工作你自己:

scala> implicit class Listable[A](val value: A) { 
    | def ::[B >: A](other: B): List[B] = other :: value :: Nil 
    | } 
defined class Listable 

scala> val xs = 1 :: 2 :: 3 :: 4 
xs: List[Int] = List(1, 2, 3, 4) 

scala> val ys = "A" :: "B" :: "C" 
ys: List[String] = List(A, B, C) 

scala> 
相关问题