为什么queue.get()返回空列表?
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())
}
}
Run Code Online (Sandbox Code Playgroud)
我怎么能得到第一个元素?
Dao*_*Wen 35
它没有返回空列表,它返回Unit(零元组),这是Scala void在Java中的等价物.如果它返回空列表,你会看到List()打印到控制台而不是()(nullary元组).
问题是你的get方法使用了错误的语法.您需要使用an =来表示get返回值:
def get() = {
this.queue.head
}
Run Code Online (Sandbox Code Playgroud)
或者这可能更好:
def get = this.queue.head
Run Code Online (Sandbox Code Playgroud)
在Scala中,您通常会忽略没有副作用的无效函数的括号(参数列表),但这需要您在调用时保留括号queue.get.
您可能希望快速查看Scala样式指南,特别是有关方法的部分.