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?
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.
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.
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.
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.
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.
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.
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