一、top-level函数和top-level属性
1. top-level函数
不依赖于任何类的静态函数,经Kotlin编译成Java文件后,成为:<静态函数所在的文件名> + "Kt"的Java类的静态成员函数。如果原kotlin文件的文件名首字母为小写时,转换成大写。
举例:
/** joinsample.kt */
package com.example.kotlin
import java.lang.StringBuilder
fun <T> joinToString(
collection: Collection<T>,
separator: String = ", ",
prefix: String = "",
postfix: String = ""
): String {
val result = StringBuilder(prefix)
for ((index, element) in collection.withIndex()) {
if (index > 0) {
result.append(separator)
}
result.append(element)
}
result.append(postfix)
return result.toString()
}
如果需要在Java中调用该方法时:
import com.example.kotlin.JoinsampleKt;
import java.util.Arrays;
import java.util.List;
public class JavaSample {
public static void main(String[] args) {
List<String> list = Arrays.asList("hello", "world");
JoinsampleKt.joinToString(list, ", ", "", "");
}
}
如果想要改变top-level的默认Java类名,可通过注解的方式修改:
@file:JvmName("StringFunctions")
package com.example.kotlin
import java.lang.StringBuilder
fun <T> joinToString(
collection: Collection<T>,
separator: String = ", ",
prefix: String = "",
postfix: String = ""
): String {
val result = StringBuilder(prefix)
for ((index, element) in collection.withIndex()) {
if (index > 0) {
result.append(separator)
}
result.append(element)
}
result.append(postfix)
return result.toString()
}
网友评论