代码之家  ›  专栏  ›  技术社区  ›  Bart van Heukelom

使用另一个内联lambda参数调用内联lambda

  •  1
  • Bart van Heukelom  · 技术社区  · 8 年前

    我试图让这个高阶Kotlin函数:

    private inline fun <T> reentrant(entered: ThreadLocal<Boolean>, block: () -> T, enter: (() -> T) -> T) =
        if (entered.get()) block()
        else {
            try {
                entered.set(true)
                enter(block)
            } finally {
                entered.set(false)
            }
        }
    

    要像这样使用,例如:

    reentrant(fooing, block) { b ->
      try {
        log("Entering a state of foo")
        b()
        // sidenote: while writing this question it dawned on me,
        //           that i could just calll the captured `block` here,
        //           as a workaround
      } finally {
        log("Foo nevermore")
      }
    }
    

    然而,显然 enter(block) 这是不允许的( Illegal usage of inline parameter block ).

    既然这里的一切都是内联的,我认为这在技术上应该是可能的。编译器不支持这个功能吗?还是我有办法做到这一点?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Yoni Gibbs    8 年前

    如果你做这样的事情,你也会犯同样的错误 val x = block 。如果您试图将Kotlin反编译为字节码,您将看到的最后一个错误是:

    Trying to access skipped parameter

    我认为关键是,当你内联某个东西时,它不再是代码中的一个对象,所以你不能直接引用它。显然,只调用函数本身是可以的,因为这已经内联到了调用代码中。

    这将得到更详细的解释 here .当函数参数内联时,没有 Function 对象已创建。我想知道在你的问题中,你的意思是:“为什么编译器不内联?” enter 然后内联 block 为什么?“我猜原因是,这将假定 进来 是调用吗 块 .但如果没有呢?如果它想存储对它的引用,例如在将来某个时候调用的函数列表中,该怎么办?它不能这样做,因为没有 作用 对象以供其引用。