Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala. Get first element of List

Tags:

list

scala

Why does queue.get() return empty list?

class MyQueue{
  var queue=List[Int](3,5,7)

  def get(){
    this.queue.head
  }
}

object QueueOperator {
  def main(args: Array[String]) {
    val queue=new MyQueue
    println(queue.get())
  }
}

How i can get first element?

like image 372
user2009490 Avatar asked Aug 25 '13 04:08

user2009490


People also ask

How do I access elements in Scala list?

List in Scala contains many suitable methods to perform simple operations like head(), tail(), isEmpty(). Coming to list, head() method is used to get the head/top element of the list. below are examples to get first element of list.

What is some () in Scala?

Scala some class returns some value if the object is not null, it is the child class of option. Basically, the option is a data structure which means it can return some value or None. The option has two cases with it, None and Some. We can use this with the collection.

What is sequence in Scala?

Sequence is an iterable collection of class Iterable. It is used to represent indexed sequences that are having a defined order of element i.e. guaranteed immutable. The elements of sequences can be accessed using their indexes.

What is the difference between Array and list in Scala?

Following are the point of difference between lists and array in Scala: Lists are immutable whereas arrays are mutable in Scala. Lists represents a linked list whereas arrays are flat.


2 Answers

It's not returning the empty list, it's returning Unit (a zero-tuple), which is Scala's equivalent of void in Java. If it were returning the empty list you'd see List() printed to the console rather than the () (nullary tuple).

The problem is you're using the wrong syntax for your get method. You need to use an = to indicate that get returns a value:

def get() = {
  this.queue.head
}

Or this is probably even better:

def get = this.queue.head

In Scala you usually leave off the parentheses (parameter list) for nullary functions that have no side-effects, but this requires you to leave the parentheses off when you call queue.get as well.

You might want to take a quick look over the Scala Style Guide, specifically the section on methods.

like image 121
DaoWen Avatar answered Oct 03 '22 21:10

DaoWen


Sometimes it can be good to use

take 1

instead of head because it doesnt cause an exception on empty lists and returns again an empty list.

like image 28
hendrik Avatar answered Oct 03 '22 19:10

hendrik