scala学习笔记-List中::使用的注意事项

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011890101/article/details/84950202

List中::使用的注意事项

::的使用

val a = List(1,2,3,4,5)
val b = 0 :: a
print(b)

上述会输出List(0, 1, 2, 3, 4, 5)

println(1 :: 2 :: 3)为什么不行
::是List中的一个函数,其中左边是参数,所以1 :: 2 :: 3会被翻译为 3.::(2).::(1),因为3是一个Int类型,并不支持::所以会报错。
可以换种方式:1 :: 2 :: 3 :: Nil,
因为Nil本身即是一个空的List,所以执行通过,代码被翻译为 Nil.::(3).::(2).::(1)

猜你喜欢

转载自blog.csdn.net/u011890101/article/details/84950202