Why is Nil required at the end of a list built using the cons operator

前端 未结 3 801
一个人的身影
一个人的身影 2020-12-06 20:50

I\'m learning Scala at the moment (Programming Scala, 2nd Edition, Odersky).

When building a list using the cons operator we have to write:

val l = 1         


        
3条回答
  •  一向
    一向 (楼主)
    2020-12-06 21:49

    Actually, you can make it work yourself:

    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>
    

提交回复
热议问题