💬

[Kotlin] forEach の仕組み

2022/02/24に公開

Kotlin forEach の仕組み

つまり

実験コード

fun main(){
  listOf("a", "b", "c")
  .forEach{e ->
    println(e)
  }
}
$ kotlinc ./Foreach.kt -include-runtime -d ./Foreach.jar
$ unzip Foeach.jar
$ javap -p -v -s -constants ForeachKt.class
public static final void main();
  descriptor: ()V
  flags: (0x0019) ACC_PUBLIC, ACC_STATIC, ACC_FINAL
  Code:
    stack=3, locals=6, args_size=0
       0: iconst_3
       1: anewarray     #8                  // class java/lang/String
       4: astore_0
       5: aload_0
       6: iconst_0
       7: ldc           #10                 // String a
       9: aastore
      10: aload_0
      11: iconst_1
      12: ldc           #12                 // String b
      14: aastore
      15: aload_0
      16: iconst_2
      17: ldc           #14                 // String c
      19: aastore
      20: aload_0
      21: invokestatic  #20                 // Method kotlin/collections/CollectionsKt.listOf:([Ljava/lang/Object;)Ljava/util/List;
      24: checkcast     #22                 // class java/lang/Iterable
      27: astore_0
      28: nop
      29: iconst_0
      30: istore_1
      31: aload_0
      32: invokeinterface #26,  1           // InterfaceMethod java/lang/Iterable.iterator:()Ljava/util/Iterator;
      37: astore_2
      38: aload_2
      39: invokeinterface #32,  1           // InterfaceMethod java/util/Iterator.hasNext:()Z
      44: ifeq          75
      47: aload_2
      48: invokeinterface #36,  1           // InterfaceMethod java/util/Iterator.next:()Ljava/lang/Object;
      53: astore_3
      54: aload_3
      55: checkcast     #8                  // class java/lang/String
      58: astore        4
      60: iconst_0
      61: istore        5
      63: getstatic     #42                 // Field java/lang/System.out:Ljava/io/PrintStream;
      66: aload         4
      68: invokevirtual #48                 // Method java/io/PrintStream.println:(Ljava/lang/Object;)V
      71: nop
      72: goto          38
      75: nop
      76: return

Discussion