在编程中,注释是为了让你和你的同事程序员理解代码而设计的程序的一部分。Kotlin 编译器(Kompiler)会完全忽略它们。
与 Java 类似,Kotlin 中有两种注释:
/* ... */
// ....
传统注释 /* ... */
这是一个可以跨越多行的多行注释。Kotlin 编译器会忽略从 /*
到 */
的所有内容。例如:
/* This is a multi-line comment.
* The problem prints "Hello, World!" to the standard output.
*/
fun main(args: Array<String>) {
println("Hello, World!")
}
传统注释也用于记录 Kotlin 代码(KDoc),但略有不同。KDoc 注释以 /**
开始,以 */
结束。
行尾注释 //
编译器会忽略从 //
到行尾的所有内容。例如:
// Kotlin Hello World Program fun main(args: Array<String>) { println("Hello, World!") // outputs Hello, World! on the screen }
上面的程序包含两个行尾注释。
// Kotlin Hello World Program
和
// outputs Hello, World! on the screen
正确使用注释
注释不应作为解释写得不好的代码的英文替代品。编写结构良好、易于阅读的代码,然后再使用注释。
有些人认为代码应该是自文档化的,注释应该很少。然而,我完全不同意(这是我的个人观点)。使用注释来解释复杂的算法、正则表达式或你为了解决问题而选择一种技术而非另一种(供将来参考)的情况,并没有什么错。
在大多数情况下,使用注释来解释“为什么”而不是“如何”去做,你就能做得很好。