// avoid if type checks//Do notfuntestTypeCheck(any:Any){if(anyisBook){println(any.isbn)}}//DofuntestTypeCheck0(any:Any){(anyas?Book)?.let{println(it.isbn)}}
// Do notfuncomsumeNullableBoolean(){varisOK:Boolean?=nullif(isOK!=null&&isOK){//do something}}//DofuncomsumeNullableBoolean0(){varisOK:Boolean?=nullif(isOK==true){//do something}}
//Do notfuntestIfElse(success:Boolean){varmessage:Stringif(success){message="恭喜,成功了"}else{message="再接再厉"}println(message)}//DofuntestIfElse1(success:Boolean){valmessage=if(success){"恭喜,成功了"}else{"再接再厉"}}//DofuntestWhen0(type:Int){valtypeString=when(type){1->"post"2->"status"else->"page"}//can't reassign value to typeString}fungetWebContent(url:String):String=TODO()//DofuntestTryCatch(){valcontent=try{getWebContent("https://droidyue.com")}catch(e:IOException){null}//can’t reassign value to content}
data classRequest(valuri:String)//use also//Do notfunhandleRequest(request:Request):Boolean{returnwhen{request.uri.startsWith("https")->{handleHttpsRequest(request)true}request.uri.startsWith("http")->{handleHttpRequest(request)true}else->false}}//DofunhandleRequest1(request:Request):Boolean{returnwhen{request.uri.startsWith("https")->true.also{handleHttpsRequest(request)}request.uri.startsWith("http")->true.also{handleHttpRequest(request)}else->false}}
data classNewsItem(valcontent:String,valisFake:Boolean)//Do notfunnormalLambda(){arrayOf<NewsItem>().filter{it.isFake}.let{print(it)}}//Do funmethodReference(){arrayOf<NewsItem>().filter(NewsItem::isFake).let(::print)}
funparseArguments(arguments:Map<String,String>){//do some bad things//try to clear if the argument is available to be cleared.(argumentsas?HashMap)?.clear()}//use read-only collections as much as possible//Do notfunuseMutableCollections(){valarguments=hashMapOf<String,String>()arguments["key"]="value"parseArguments(arguments)}//Do funuseReadOnlyCollections(){valarguments=mapOf("key"to"value")parseArguments(arguments)}
适宜情况下使用Pair或Triple
12345678
// Use Pair or TriplefunreturnValues():Pair<Int,String>{returnPair(404,"File Not Found")}funreturnTriple():Triple<String,String,String>{returnTriple("6时","6分","60秒")}
使用lazy 替代繁琐的延迟初始化
12345678910111213141516171819202122
data classConfig(valhost:String,valport:Int)funloadConfigFromFile():Config=TODO()//Do notobjectConfigManager{varconfig:Config?=nullfungetConfig0():Config?{if(config==null){config=loadConfigFromFile()}returnconfig}}//DoobjectConfigManager1{valconfig:Configbylazy{loadConfigFromFile()}}