@946898963
2020-07-09T08:16:03.000000Z
字数 2441
阅读 1323
Kotlin
文件名命名遵守大驼峰规则(首字母大写)
如果一个文件中仅包含一个class, 那么则应该以该类的名称来命名文件
// Main.KTclass Main {fun print() {println("Hello World.")}}
如果一个文件中包含多个top-level declarations(顶级的类/方法/变量/常量等), 则可以选一个合适名字命名
// ServiceInfo.KTdata class AreaInfo(val areaImg: String,val areaTotal: Int)data class AvgPrice(val title: String,val amount: String,val unit: String)data class ServiceInfo(// 服务区域val serviceAreaInfo: AreaInfo?,// 服务报价val serviceAvgPrice: AvgPrice?)
一个文件可以包含多个top-level declarations, 但是需要尽可能的保证以下几点:
尽可能的保证文件中的top-level declarations 都是相关联的(例如: 一组拓展函数, 一组Bean类)
尽可能的保证文件中的publish属性的数量是最小的
同Java中的写法, 类名命名遵守大驼峰规则(首字母大写), 方法名命名遵守小驼峰规则(首字母小写)
class Main {fun print() {println("Hello World.")}}
lass Person {val mName: String = "石硕"val mHeight: Int = 190fun print() {println(TEXT_PRINT)}companion object {const val TEXT_PRINT = "Hello World."}}
class Person {val sex: Int = Sex.MANval height: Int = 190val name: String = "石硕"val country: String = CHINAfun print() {println(TEXT_PRINT)}companion object {const val TEXT_PRINT = "Hello World."// 定义在companion object中const val CHINA = "china"const val OTHER = "other"}object Sex {// 定义在自定义的Object中const val MAN = 0const val WOMAN = 1}}
// Kotlinclass TestConst {companion object {const val TEXT = "Text."val TEXT_WITHOUT_CONST = "Text without Const."@JvmFieldval TEXT_WITH_JVM_FIELD = "Text without Const but with JvmField"@JvmStaticval TEXT_WITH_JVM_STATIC = "Text without Const but with JvmStatic"}}// Javaclass JAVATest {public static void main(String[] args) {// 调用Const常量System.out.println(TestConst.TEXT);// 调用非Const常量System.out.println(TestConst.Companion.getTEXT_WITHOUT_CONST());// 调用非Const但是用@JvmStatic修饰的常量(两种调用方式都可以)System.out.println(TestConst.getTEXT_WITH_JVM_STATIC());System.out.println(TestConst.Companion.getTEXT_WITH_JVM_STATIC());// 调用非Const但是用@JvmField修饰的常量System.out.println(TestConst.TEXT_WITH_JVM_FIELD);}}
正确

错误

class Foo {fun bar(obj: Any) {val v = V()obj.let {// 这样有问题v.methodA(null) {v.methodB(null) {}}// 这样没问题v.methodA(null) {}v.methodB(null) {}}}private class V {fun methodA(s: String?, callback: (Boolean) -> Unit) {}fun methodB(s: String?, callback: (Boolean) -> Unit) {}}}