Kotlin中的数组、字符串、函数、Java互操作性及集合
1. Kotlin与Java的互操作性
1.1 异常声明问题
在Kotlin中,如果一个函数抛出异常,但在Java代码中调用时没有声明该异常,会导致错误。例如:
// samples Kotlin function
// filename example.kt
package Samples
fun print(){
throws IOException()
}
// Java code trying to call the above function
try {
Samples.Example.print();
}
// This statement causes error because it does
// not declare IOexception in throws list
catch(IOException e) {
}
为了解决这个问题,我们可以在Kotlin函数开始处使用 @Throws 注解:
// Overcoming problem with @Throws annotation
package Samples
@Throws(IOException::class)
fun print()
{
throws IOException()
}
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



