目前,我使用它来挑选列表的第一个元素:
def Get_Read_Key =
{
logger.entering (TAG, "Get_Read_Key")
val Retval = if (Read_Key_Available)
{
val Retval = Keystrokes.head
Keystrokes = Keystrokes.tail
Retval
}
else
{
calculator.ui.IKey.No_Key
} // if
logger.exiting (TAG, "Get_Read_Key", Retval)
Retval
} // Get_Read_Key
def Read_Key_Available = Keystrokes.size > 0但它看起来有点笨拙--尤其是双重的“Retval”。有没有更好的方法来做这件事?或者这仅仅是使用不可变列表的代价?
背景:该例程用于单元测试模拟类-返回类型已设置。
发布于 2012-08-21 14:25:56
你正在List上实现一个Iterator,它已经在标准库中了。
val it = Keystrokes.iterator
def Read_Key_Available = it.hasNext
def Get_Read_Key = if(it.hasNext) it.next() else calculator.ui.IKey.No_Key发布于 2012-08-21 15:00:34
如果Keystrokes列表的第一个元素不为空,则下面的代码将获取该元素,否则将获取calculator.ui.IKey.No_Key:
Keystrokes.headOption.getOrElse( calculator.ui.IKey.No_Key )附注:将Keystrokes重新分配到尾部是一个糟糕设计的明确标志。相反,你应该在你的算法中使用themel提到的列表已经存在的迭代功能。使用诸如map或foreach之类的方法很可能会解决您的问题。
附注:你已经违反了几个Scala naming conventions
以lowercase
camelCase开头的有特殊处理,因此极不鼓励使用下划线来实现这些目的
发布于 2012-08-21 14:21:57
您可以使用模式匹配:
Keystrokes match {
case h::t =>
KeyStrokes = t
h
case _ =>
calculator.ui.IKey.No_key
}https://stackoverflow.com/questions/12049261
复制相似问题