hier ps
ist vom Typ Sammel-Stream, die tatsächlich eine Variable ist aber wie sein mögliches es zu nennen wie diese ps (10000) als nicht jede Methode
Es ist möglich, ps(10000)
weil Stream
zu nennen hat eine apply
Methode (geerbt von LinerSeqOptimized
):
/** Selects an element by its index in the $coll.
* Note: the execution of `apply` may take time proportial to the index value.
* @throws `IndexOutOfBoundsException` if `idx` does not satisfy `0 <= idx < length`.
*/
def apply(n: Int): A = {
val rest = drop(n)
if (n < 0 || rest.isEmpty) throw new IndexOutOfBoundsException("" + n)
rest.head
}
()
auf jedem Objekt aufrufen in Scala lässt den Compiler nach einer apply
Methode auf dem Objekt suchen. Dies ist vergleichbar mit der Möglichkeit, Fallklassen ohne das Schlüsselwort new
zu instanziieren, da der Compiler automatisch apply
und unapply
für Sie generiert.
Wenn wir ein einfacheres reproduce aussehen werden:
def main(args: Array[String]): Unit = {
val ps: Stream[Int] = Stream.from(1, 1)
val r = ps(1)
println(r)
}
Der Compiler tatsächlich tut:
val r = ps.apply(1)
Wo apply
für eine Sammlung in der Regel das Element am Index nachschlägt i
:
scala> val ps: Stream[Int] = Stream.from(1, 1)
ps: Stream[Int] = Stream(1, ?)
scala> val r = ps(1)
r: Int = 2
scala> val x = ps.apply(1)
x: Int = 2
Wenn Sie tatsächlich sehen wollen, was die comp Iler erzeugt:
object Problem7 extends Object {
def main(args: Array[String]): Unit = {
val ps: scala.collection.immutable.Stream = scala.`package`.Stream().from(1, 1);
val r: Int = scala.Int.unbox(ps.apply(1));
scala.this.Predef.println(scala.Int.box(r))
};
def <init>(): Problem7.type = {
Problem7.super.<init>();
()
}
}
}
Gibt es einen Grund, warum Sie keine Methode anstelle einer Variablen deklarieren? –
kein Grund, nur zu versuchen zu verstehen, wie es funktioniert – Aamir