为什么在Scala Option中创建这样的单个元素列表?

Dra*_*orn 1 scala

/** Returns a singleton list containing the $option's value
* if it is nonempty, or the empty list if the $option is empty.
*/  
def toList: List[A] =
  if (isEmpty) List() else new ::(this.get, Nil)
Run Code Online (Sandbox Code Playgroud)

什么时候可以使用

  if (isEmpty) List() else List(this.get)
Run Code Online (Sandbox Code Playgroud)

小智 5

既然你的版本(即List(this.get))更具可读性并产生相同的结果,我愿意打赌这纯粹是一种优化.也就是说,要获得非空列表,必须在某个时刻调用List构造函数("new ::") - 最快的方法就是直接调用它.

在List.apply的实现中:

override def apply[A](xs: A*): List[A] = xs.toList
Run Code Online (Sandbox Code Playgroud)

构造函数调用至少需要两个额外的堆栈帧(List.apply,然后是xs.toList).

  • 编译器中有一个特殊情况,它将`List()`优化为`Nil`.这就是为什么.但我很同意,这很难看. (2认同)