2017-08-01 52 views
0

我有以下的集合:斯卡拉ifNotPresent簡潔的形式

private val commandChain: mutable.Buffer[mutable.Buffer[Long]] = ArrayBuffer() 

我需要做到以下幾點:

def :->(command: Long) = { 
    commandChain.headOption match { 
    case Some(node) => node += command 
    case None => commandChain += ArrayBuffer(command) 
    } 
} 

是否有這種更簡潔的形式比模式匹配?

回答

1

你可以用一個簡單的if ... else聲明去。沒有圖案匹配,也沒有Option展開。

def :->(command: Long): Unit = 
    if (commandChain.isEmpty) commandChain += ArrayBuffer(command) 
    else      commandChain.head += command 

順便說一句,這是更方式可變數據結構和副作用比在大多數慣用(即「好」)的Scala看出。

+0

您的意思是這個速度更快? –

+0

也許,但我認爲你會很難找到可衡量的性能差異。這只是稍微簡潔一些,並提供更多的可讀性和清晰度的目的,恕我直言。 – jwvh