scalascala-collections

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.


Solution

  • The element can be retrieved using index-based access 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.
    }