0
/** A lazy cons cell, from which streams are built. */
  @SerialVersionUID(-602202424901551803L)
  final class Cons[+A](hd: A, tl: => Stream[A]) extends Stream[A] with Serializable {
    override def isEmpty = false
    override def head = hd
    @volatile private[this] var tlVal: Stream[A] = _
    def tailDefined: Boolean = tlVal ne null
    override def tail: Stream[A] = {
      if (!tailDefined)
        synchronized {
          if (!tailDefined) tlVal = tl
        }

      tlVal
    }
  }

通配符_代表@volatile private[this] var tlVal: Stream[A] = _什么?

4

1 回答 1

2

通配符为 a 分配一个默认值var,这使得变量初始化并准备好使用;据我所知,这将null适用于任何来自sAnyRef的“默认”值AnyVal(对于0数字等)。falseBoolean

您不能声明但未定义的局部变量。例子说明了很多:

scala> var a : Int = _
a: Int = 0

scala> var b : String = _
b: String = null

scala> var bool : Boolean = _
bool: Boolean = false

scala> var c : Long
<console>:7: error: only classes can have declared but undefined members
(Note that variables need to be initialized to be defined)
       var c : Long
于 2013-10-25T21:02:24.970 回答