user2009490
user2009490

Reputation: 348

Scala. Get first element of List

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?

Upvotes: 30

Views: 66903

Answers (2)

hendrik
hendrik

Reputation: 2042

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.

Upvotes: 2

DaoWen
DaoWen

Reputation: 33029

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.

Upvotes: 41

Related Questions