爲什麼這個Scala代碼:爲什麼Scala在拆包Tuple時構造一個新的Tuple?
class Test
{
def foo: (Int, String) =
{
(123, "123")
}
def bar: Unit =
{
val (i, s) = foo
}
}
產生bar()
是構建一個新的Tuple2
以下的字節碼,通過從foo()
給它的Tuple2
,然後獲取值出來的嗎?
public void bar();
Code:
0: aload_0
1: invokevirtual #28; //Method foo:()Lscala/Tuple2;
4: astore_2
5: aload_2
6: ifnull 40
9: new #7; //class scala/Tuple2
12: dup
13: aload_2
14: invokevirtual #32; //Method scala/Tuple2._1:()Ljava/lang/Object;
17: aload_2
18: invokevirtual #35; //Method scala/Tuple2._2:()Ljava/lang/Object;
21: invokespecial #20; //Method scala/Tuple2."<init>":(Ljava/lang/Object;Ljava/lang/Object;)V
24: astore_1
25: aload_1
26: invokevirtual #39; //Method scala/Tuple2._1$mcI$sp:()I
29: istore_3
30: aload_1
31: invokevirtual #35; //Method scala/Tuple2._2:()Ljava/lang/Object;
34: checkcast #41; //class java/lang/String
37: astore 4
這是因爲編譯器不檢查foo()
返回值是不是一個元組?
無論如何,JVM會優化建築嗎?
'foo'的返回值_is_是一個元組。你爲什麼認爲它不是? –
foo確實返回了一個類型,但是在9:in bar()中它構造了一個新的元組。 –