2017-06-04 143 views
0

Exceptions.kt内联函数:呼叫科特林从Java

@Suppress("NOTHING_TO_INLINE") 
inline fun generateStyleNotCorrectException(key: String, value: String) = 
     AOPException(key + " = " + value) 

在科特林:

fun inKotlin(key: String, value: String) { 
    throw generateStyleNotCorrectException(key, value) } 

它工作在科特林和内联函数。

但在Java代码中使用时,它只是不能被内联, 和仍然正常的静态方法调用(从反编译的内容所示)。

事情是这样的:

public static final void inJava(String key, String value) throws AOPException { 
    throw ExceptionsKt.generateStyleNotCorrectException(key, value); 
// when decompiled, it has the same contents as before , not the inlined contents. 
} 
+3

为什么会首先期望Java编译器可以神奇地内联函数? Java知道Java方法。它应该如何知道其他语言的概念? – GhostCat

回答

5

这年代由科特林编译器完成不支持Java文件,因为Java编译器不知道这种转变(见this answer为什么物化仿制药没有从工作的内联Java)。

至于其他内联使用情况(通常以lambda作为参数传递时),正如您已经发现的那样,字节码包含一个public static方法,以便仍可从Java调用内联函数。但是,在这种情况下,不会发生内联。