Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print first element in list using Scala

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.

like image 682
Michael Avatar asked Sep 21 '13 13:09

Michael


People also ask

How do I access elements in Scala list?

We can use the head() and last() methods of the class List to get the first and last elements respectively.

Does Scala list preserve order?

Lists preserve order, can contain duplicates, and are immutable.

What is a SEQ in Scala?

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.


1 Answers

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.
}
like image 135
Branislav Lazic Avatar answered Sep 30 '22 13:09

Branislav Lazic