How can I print the first element in list using Scala?
For example in Python I can just write:
>>>l = [1,2,3,4]
>>>one = l[0]
>>>print one
How can I do that on Scala
Thanks.
We can use the head() and last() methods of the class List to get the first and last elements respectively.
Lists preserve order, can contain duplicates, and are immutable.
Scala Seq is a trait to represent immutable sequences. This structure provides index based access and various utility methods to find elements, their occurences and subsequences. A Seq maintains the insertion order.
As Hiura said, or like this:
object ListDemo extends App {
val lst = List(1, 2, 3)
println(lst(0)) // Prints specific value. In this case 1.
// Number at 0 position.
println(lst(1)) // Prints 2.
println(lst(2)) // Prints 3.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With