Kotlin安卓開(kāi)發(fā)指南_第1頁(yè)
Kotlin安卓開(kāi)發(fā)指南_第2頁(yè)
Kotlin安卓開(kāi)發(fā)指南_第3頁(yè)
Kotlin安卓開(kāi)發(fā)指南_第4頁(yè)
Kotlin安卓開(kāi)發(fā)指南_第5頁(yè)
已閱讀5頁(yè),還剩209頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

什么是Android在AndroidStudio中創(chuàng)建一個(gè)項(xiàng)目創(chuàng)建一個(gè)TheRecycler使Forecastlist可點(diǎn)擊ForecastListAdapter的clicklistenerKotlinAndroid怎么去使用KotlinAndroid實(shí)現(xiàn)Flowcontrol和ranges提供一個(gè)新的訪問(wèn)SharedPreferences測(cè)試你的UnittestingInstrumentationtests如果你覺(jué)得Java7是一個(gè)過(guò)期的語(yǔ)言,并決定找一個(gè)更現(xiàn)代的語(yǔ)言代替。恭喜你!就如你知道的,雖然Java8已經(jīng)發(fā)布了,它包含了很多設(shè)備過(guò)期、幾乎沒(méi)有人使用它們之前我們也不能使用Java8,所以恐什么是什么是\hAndroidStudio,官方的AndroidIDE,就是基于Intellij,作對(duì)Java開(kāi)發(fā)者來(lái)說(shuō),Kotlin是非常直覺(jué)化的,并且非常容易學(xué)它與我們?nèi)粘I钍褂玫腎DE無(wú)需配置就能完全整合。Android它更加安全:Kotlin是空安全的,也就是說(shuō)在我們編譯時(shí)期就處它是函數(shù)式的:Kotlin是基于面向?qū)ο蟮恼Z(yǔ)言。但是就如其他很它是高度互操作性的:你可以繼續(xù)使用所有的你用Java寫的代碼我們通過(guò)我們通過(guò)Kotlin我們通過(guò)Kotlin得到什么易表現(xiàn)publicclassArtist{privatelongid;privateStringname;privateStringurl;privateStringpubliclonggetId(){returnid;publicvoidsetId(longid){this.id=id;publicStringgetName()return publicvoidsetName(Stringname)= publicStringgetUrl()return publicvoidsetUrl(Stringurl)this.url= publicStringgetMbid()return publicvoidsetMbid(Stringmbid)this.mbid= @OverridepublicStringtoString()return"Artist{""id="+id",name='"+name+'\''",url='"+url+'\''",mbid='"+mbid+'\'' 48.1.1.dataclassvarid:Long,varname:String,varurl:String,varmbid:

這里不能通過(guò)編譯Artist不能是varnotNullArtist:Artist=//Artist可以是varartist:Artist?=無(wú)法編譯artist可能是null,我們需要進(jìn)行處理只要在artistnull時(shí)才會(huì)打印智能轉(zhuǎn)換if(artist!=null){只有在確保artist不是null使用Elvis操作符來(lái)給定一個(gè)在是nullvalname=artist?.name?:funfunFragment.toast(message:CharSequence,duration:Int=Toast.LENGTH_SHORT){Toast.makeText(getActivity(),message,3.1.1.fragment.toast("Hello函數(shù)式支持1.1.view.setOnClickListener{toast("Helloworld!")AndroidAndroidAndroidAndroidStudioAndroid第一件事就是安裝AndroidStudio。就如你知道的,AndroidAndroidStudio是\hIntellijIDEA的插件實(shí)現(xiàn),IntellijIDEA\h轉(zhuǎn)移到AndroidStudio是Android開(kāi)發(fā)者一個(gè)重要的改變。首先,\hAndroidStudio了。Kotlin團(tuán)隊(duì)也創(chuàng)建了一個(gè)針對(duì)Eclipse的插\h安裝安裝Kotlin現(xiàn)。前往AndroidStudio的

Kotlin:這是一個(gè)基礎(chǔ)的插件。它能讓AndroidStudio懂得KotlinAndroidExtensions:Kotlin團(tuán)隊(duì)還為Android開(kāi)發(fā)發(fā)布了另外一個(gè)有趣的插件。這個(gè)AndroidExtensions可以因?yàn)閺腎ntellij15開(kāi)始,插件是被默認(rèn)安裝了的,但是你的AndroidStudio可能并沒(méi)有。所以你需要進(jìn)入AndroidStudio\hBeginnersCourseinUdacity。我們可能會(huì)關(guān)注不同的事情,但在在AndroidStudio在AndroidStudio在AndroidStudioCreatenewCreatenew

WeatherWeather下一步,它會(huì)讓你選擇最小的API版本。我們選擇API15,因?yàn)槲覀傾ddnoAddnoBlankBlank

配置配置配置配置 buildscriptbuildscriptext.support_version=ext.kotlin_version=ext.anko_version=repositoriesdependenciesclasspath classpath"org.jetbrains.kotlin:kotlin-gradle- 12.allprojectsrepositories 17.

supportsupport

AndroidExtensionsAndroidExtensionsapplyplugin:'com.android.application'applyplugin:'kotlin-android'applyplugin:'kotlin-android-extensions'android{dependenciescompile"com.android.support:appcompat-v7:$support_version"compile"org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"compile"org.jetbrains.anko:anko-common:$anko_version"buildscriptrepositories{dependenciesclasspath"org.jetbrains.kotlin:kotlin-android- 把把MainActivity轉(zhuǎn)換成KotlinKotlinplugin包含了一個(gè)有趣的特性,它能把Java代碼轉(zhuǎn)成ConvertJavaConvertJavaFiletoKotlin

我們想再將編寫一些代碼來(lái)測(cè)試KotlinAndroidExtensions是否 1.1.import overrideoverridefunonCreate(savedInstanceState:Bundle?)message.text="Hello5. \h的新的內(nèi)容。如果你有疑問(wèn)或者想查看代碼,請(qǐng)?jiān)贙otlinforAndroidDevelopersrepository查看。每個(gè)章節(jié)只要修改了代\h classclass3.1.1.classPerson(name:String,surname: classclassPerson(name:String,surname:String) 5.

openopenclassAnimal(name:classPerson(name:String,surname:String): funfunonCreate(savedInstanceState:Bundle?)

funfunadd(x:Int,y:Int):Intreturnx+3.1.1.funadd(x:Int,y:Int):Int=x+funfunadd(x:Int,y:Int):Intreturnx+3.funfuntoast(message:String,length:Int=Toast.LENGTH_SHORT)Toast.makeText(this,message,3.toast("Hello",voidvoidtoast(Stringvoidvoidtoast(Stringmessage,intToast.makeText(this,message,6.funfunniceToast(message: tag:String=javaClass<MainActivity>length:Int=Toast.LENGTH_SHORT)Toast.makeText(this,"[$className]$message",5.toast("Hello",toast("Hello","MyTag",1.1.toast(message="Hello",length=上編寫復(fù)雜的String。在上面的例子中,我使用了”[$className]$message”。如你所見(jiàn),任何時(shí)候你使用一 符號(hào)就可以插入一個(gè)表達(dá)式。如果這個(gè)表達(dá)式有點(diǎn)復(fù)雜,你就需要使用一對(duì)大括號(hào)括起來(lái):”Yournameis${}” 創(chuàng)建一個(gè)創(chuàng)建一個(gè)創(chuàng)建一個(gè)創(chuàng)建一個(gè) dependenciesdependenciescompilefileTree(dir:'libs',include:5. \h valvalforecastList=findViewById(R.id.forecast_list)asforecastList.layoutManager=

符 創(chuàng)建了一個(gè)對(duì)象的實(shí)例TheRecyclerTheRecyclerTheRecyclerTheRecyclerAdapterTheRecycler\h \h\h\h \h\h

classclassForecastListAdapter(valitems:List<String>)overridefunonCreateViewHolder(parent:ViewGroup,viewType:Int):ViewHolder{returnoverridefunonBindViewHolder(holder:ViewHolder,position:Int){holder.textView.text=overridefungetItemCount():Int=classViewHolder(valtextView:TextView): privateprivatevalitems="Mon6/23-Sunny-"Tue6/24-Foggy-"Wed6/25-Cloudy-"Thurs6/26-Rainy-"Fri6/27-Foggy-"Sat6/28-TRAPPEDINWEATHERSTATION-"Sun6/29-Sunny-overridefunonCreate(savedInstanceState:Bundle?)valforecastList=findViewById(R.id.forecast_list)asforecastList.layoutManager=LinearLayoutManager(this)forecastList.adapter=ForecastListAdapter(items)使用一個(gè)函數(shù)listOf創(chuàng)建一個(gè)常量的List(很快我們就會(huì)講到的immutable)。它接收一個(gè)任何類型的

(可變長(zhǎng)的參數(shù)),

valvalvald:Double=valvalvali:Int=位運(yùn)算也有一點(diǎn)不同。在Android中,我們經(jīng)常在 ////intbitwiseOr=FLAG1|intbitwiseAnd=FLAG1&//valbitwiseOr=FLAG1orvalbitwiseAnd=FLAG1and

\h字面上可以寫明具體的類型。這個(gè)不是必須的,但是一個(gè)通用的valvali=12//AnvaliHex0x0f一個(gè)十六進(jìn)制的Intvall=3L//Avald=3.5//Avalf=3.5F//Avalvals=valcs[2這是一個(gè)字符迭代vals=for(cin7.

valvals="Example"http://Avali=23//AnvalactionBar=supportActionBar//AnActionBarinanActivityvalvala:Any=valc:Context=publicpublicclassPersonprivateStringpublicStringgetName()return publicvoidsetName(Stringname)= 9.Personperson=newStringname=publicclassPerson{varname:String=""valperson=Person()="name"valname=publicpublicclasssPersonvarname:String=get()=field="Name: 7.

backingbackingbacking backing1.1.dataclassForecast(valdate:Date,valtemperature:Float,valdetails:String)hashCode()我們可以得到一個(gè)hash值,也是從屬性中計(jì)算出copy()你可以拷貝一個(gè)對(duì)象,可以根據(jù)你的需要去修改里面的

valvalf1=Forecast(Date(),27.5f,"Shinyvalf2=f1.copy(temperature= 些情況下,我們?nèi)匀豢梢孕薷倪@些狀態(tài)。在上一個(gè)例子中,你還是可以訪 另外一個(gè)方法是封裝這些類。你可以創(chuàng)建一 類,它封 并且不允許去修改它們的狀態(tài)。決定哪種方式取決于你。本書中,我不會(huì) valvalf1=Forecast(Date(),27.5f,"Shinyval(date,temperature,details)=valvaldate=valtemperature=valdetails=

forfor((key,value)inmap)Log.d("map","key:$key,3.

a+a-a*a/a%aina!ina+=a-=a*=a/=a%=a[i,a.get(i,a[i_1,…,a.get(i_1,…,a[i]=a.set(i,a[i,j]=a.set(i,j,a[i_1,…,i_n]=a.set(i_1,…,i_n,a==a?.equals(b)?:b===a!=!(a?.equals(b)?:b===1.1.operatorfunequals(other:Any?):

a(i,a.invoke(i,a(i_1,…,a.invoke(i_1,…,valvalx=myList[2]= datadataclassForecastList(valcity:String,valcountry:valdailyForecast:List<Forecast>) operatorfunget(position:Int):Forecast=funsize():Int=5. overrideoverridefunonBindViewHolder(holder:position:Int)with(weekForecast[position])holder.textView.text="$date-$description- 6. 1.1.overridefungetItemCount():Int= 1.1.operatorfunViewGroup.get(position:Int):View=

valvalcontainer:ViewGroup=valview=別忘了去\hKotlinforAndroiddevelopersrepository去查看使使Forecastlist使Forecastlist使Forecastlist可點(diǎn)擊使Forecastlist <?xmlversion="1.0"encoding="utf-\h\htools:text="May14,tools:text="LightdatadataclassForecast(valdate:String,valdescription: valhigh:Int,vallow:Int,valiconUrl: privatefunconvertForecastItemToDomain(forecast:Forecast):ModelForecast{returnModelForecast(convertDate(forecast.dt),privatefungenerateIconUrl(iconCode:String):=\h\h \h 1.1.compilepublicpublicinterfaceOnItemClickListeneroperatorfuninvoke(forecast:3. classViewHolder(view:View,valitemClick:OnItemClickListener)RecyclerView.ViewHolder(view)privatevaliconView:privatevaldateView:privatevaldescriptionView:privatevalmaxTemperatureView:privatevalminTemperatureView:initiconView=dateView=descriptionView=maxTemperatureView=minTemperatureView= funbindForecast(forecast:Forecast)with(forecast)dateView.text=descriptionView.text=maxTemperatureView.text=minTemperatureView.text=itemView.setOnClickListener{itemClick(forecast) 27.

publicclassForecastListAdapter(valweekForecast:valitemClick:ForecastListAdapter.OnItemClickListener) overridefunonCreateViewHolder(parent:ViewGroup,viewType:ViewHoldervalview=.inflate(R.layout.item_forecast,parent,returnViewHolder(view, overridefunonBindViewHolder(holder:ViewHolder,position:Int){ 16.

valvalView.ctx:get()= forecastListforecastList.adapter=object:overridefuninvoke(forecast:Forecast) Lambdas簡(jiǎn)化簡(jiǎn)化簡(jiǎn)化簡(jiǎn)化 publicpublicinterfaceOnClickListenervoidonClick(View3.viewview.setOnClickListener(newpublicvoidonClick(Viewv) Toast.makeText(v.getContext(),"Click", 6.viewview.setOnClickListener(object:OnClickListeneroverridefunonClick(v:View) 5.1.1.funsetOnClickListener(listener:(View)->1.1.view.setOnClickListener({view->1.1.view.setOnClickListener({toast("Click")1.1.view.setOnClickListener(){toast("Click")1.1.view.setOnClickListener{toast("Click")ForecastListAdapterForecastListAdapter的clickForecastListAdapter的click在前面一章,我這么艱苦地寫了clicklistener的目的就是更好的publicpublicclassForecastListAdapter(valweekForecast:valitemClick:(Forecast)-> 1.1.classViewHolder(view:View,valitemClick:(Forecast)-> 1.1.valadapter=ForecastListAdapter(result){forecast->toast(forecast.date)} 1.1.valadapter=ForecastListAdapter(result){toast(it.date) 1.1.inlinefun<T>with(t:T,body:T.()->Unit){t.body()

withwith(forecast)dateView.text=descriptionView.text=maxTemperatureView.text=minTemperatureView.text=itemView.setOnClickListener{itemClick(this)8. inlineinlinefunsupportsLollipop(code:()->Unit)if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) 5.supportsLollipopsupportsLollipop3.\h\h\hKotlin\h\h\h\h\hKotlin\h\h\h\h privateprotectedinternalpublic

根據(jù)Jetbrains的定義,一個(gè)module應(yīng)該是一個(gè)單獨(dú)的功能性的單位,它應(yīng)該是可Studio中創(chuàng)建不同的module。在Eclipse中,這 可以認(rèn)為是在 中的不同的project

1.1.classCprivateconstructor(a:Int){...

1.1.classRequestForecastCommand(privatevalzipCode: datadataclassForecastList(...)funget(position:Int)=funsize()=4.KotlinKotlinAndroidKotlinAndroidKotlinAndroidExtensionsKotlinAndroidKotlinKotlinKotlinAndroidKotlinAndroid

怎么去使用怎么去使用KotlinAndroid怎么去使用KotlinAndroid怎么去使用KotlinAndroidExtensionsAndroid AndroidAndroidAndroid怎么去使用KotlinAndroid如果你還記得,現(xiàn)在項(xiàng)目已經(jīng)準(zhǔn)備好去使用KotlinAndroid repositories dependencies classpath"org.jetbrains.kotlin:kotlin-android- 8. Android或 Android

1.1.import importimportimportAndroidAndroid 1.1.import1.1.view.textView.text=

KotlinAndroidKotlinAndroid 1.1.import \h overrideoverridefunonCreate(savedInstanceState:Bundle?)forecastList.layoutManager=LinearLayoutManager(this)

1.1.import

classclassViewHolder(view:View,valitemClick:(Forecast)->Unit)RecyclerView.ViewHolder(view)funbindForecast(forecast:Forecast)itemView.date.text=itemView.description.text=itemView.maxTemperature.text=itemView.minTemperature.text=itemView.onClick{itemClick(forecast) 13.KotlinAndroidExtensions插件幫助我們減少了很多模版代碼,ApplicationApplication單例化和屬性的個(gè)更簡(jiǎn)單的訪問(wèn)applicationcontext的方式。ApplicatonApplicatonclassclassApp:Application()companionobjectprivatevarinstance:Application?=funinstance()= overridefunonCreate()instance= 10.

classDelegate<T>:ReadWriteProperty<Any?,T>fungetValue(thisRef:Any?,property:KProperty<*>):T{return...funsetValue(thisRef:Any?,property:KProperty<*>,value:T) classclassExamplevarp:Stringby3.3. LazyObservableVetoableNotNull

值。這是非常有趣的特性,當(dāng)我們?cè)谒鼈兊谝淮握嬲{(diào)用之前不是必classApp:Application()valdatabase:SQLiteOpenHelperbylazy{overridefunonCreate(){valdb= lazy(LazyThreadSafeMode.NONE){...lazy(LazyThreadSafeMode.NONE){... 1.class1.classViewModel(valdb:MyDatabase)myPropertybyDelegates.observable("")d,old,new-db.saveChanges(this,6.

varvarpositiveNumber=Delegates.vetoable(0)d,old,new-new>=4.Not classApp:Application(){companionobject{varinstance:AppbyoverridefunonCreate(){instance=this10.10. importimportclassConfiguration(map:Map<String,Any?>)width:Intbyheight:Intbydp:IntbydeviceName:Stringby8.confconf="width"to"height"to"dp"to"deviceName"to

privateclassprivateclassNotNullSingleValueVar<T>():ReadWriteProperty<Any?,T>{ overridefungetValue(thisRef:Any?,property:KProperty<*>):T{throw overridefunsetValue(thisRef:Any?,property:KProperty<*>,value:T){GetterprivateclassprivateclassNotNullSingleValueVar<T>():ReadWriteProperty<Any?,T>{privatevarvalue:T?=overridefungetValue(thisRef:Any?,property:KProperty<*>):returnvalue?:throwIllegalStateException("${}"not overridefunsetValue(thisRef:Any?,property:KProperty<*>,value:T){this.value=if(this.value==null)elsethrowIllegalStateException("${}alreadyobjectobjectDelegatesExtfunReadWriteProperty<Any?,T>=4.重新實(shí)現(xiàn)重新實(shí)現(xiàn)Application classApp:Application(){companionobject{varinstance:AppbyoverridefunonCreate()instance=this companioncompanionobjectvarinstance:Appby3.創(chuàng)建一個(gè)創(chuàng)建一個(gè)創(chuàng)建一個(gè)創(chuàng)建一個(gè) ManagedSqliteOpenHelper

forecastDbHelperforecastDbHelper.use3. publicfunpublicfun<T>use(f:SQLiteDatabase.()->T):Ttryreturnfinally7.

valvalresult=forecastDbHelper.usevalqueriedObject=4.

objectobjectCityForecastTablevalNAME=valID=valCITY=valCOUNTRY=6.objectobjectDayForecastTablevalNAME=valID=valDATE=

DESCRIPTION=HIGH=LOW=ICON_URL=CITY_ID=10.實(shí)現(xiàn)實(shí)現(xiàn)實(shí)現(xiàn)實(shí)現(xiàn)

classclassForecastDbHelper(): ForecastDbHelper.DB_NAME,null,ForecastDbHelper.DB_VERSION){4.

companion companioncompanioncompanionobjectvalDB_NAME=valDB_VERSION=valinstance:ForecastDbHelperbylazy{ForecastDbHelper()5.

CREATE CREATE Pair(CityForecastTable.ID,INTEGER+Pair(CityForecastTable.CITY,Pair(CityForecastTable.COUNTRY,

funfunSqlType.plus(m:SqlTypeModifier):SqlTypereturnSqlTypeImpl(name,if(modifier==null)else"$modifier4. 1.1.publicfun<A,B>A.to(that:B):Pair<A,B>=Pair(this,1.1.valpair=object1toCityForecastTable.IDtoINTEGER+CityForecastTable.CITYtoCityForecastTable.COUNTRYtooverrideoverridefunonCreate(db:SQLiteDatabase)CityForecastTable.IDtoINTEGER+CityForecastTable.CITYtoCityForecastTable.COUNTRYtodb.createTable(DayForecastTable.NAME,true,DayForecastTable.IDtoINTEGER+PRIMARY_KEY+DayForecastTable.DATEtoINTEGER,DayForecastTable.DESCRIPTIONtoTEXT,DayForecastTable.HIGHtoINTEGER,DayForecastTable.LOWtoINTEGER,DayForecastTable.ICON_URLtoTEXT,DayForecastTable.CITY_IDtoINTEGER)

overrideoverridefunonUpgrade(db:SQLiteDatabase,oldVersion:Int,newVersion:Int){5.\h\h

classclassForecastDbHelper(ctx:Context=App.instance) ManagedSQLiteOpenHelper(ctx,ForecastDbHelper.DB_NAME,ForecastDbHelper.DB_VERSION)valvaldbHelper1ForecastDbHelper它會(huì)使用valdbHelper2ForecastDbHelper(mockedContextCollection:這個(gè)類相是一個(gè)范性集合。我們通過(guò)函數(shù)訪問(wèn)可以

MutableList:一個(gè)支持增加和刪除item的List。Set:一個(gè)無(wú)序并不支持重復(fù)item的集合。Map:一個(gè)key-value對(duì)的collection。key在map中是唯一anyallcountfoldfoldRightforEachforEachIndexedmaxmaxByminminBynonereducereduceRightsumByvalvallist=listOf(1,2,3,4,5,assertTrue(list.any{it%2==0assertFalse(list.any{it>10assertTrueassertTrue(list.all{it<10assertFalse(list.all{it%2==01.1.assertEquals(3,list.count{it%2==01.1.assertEquals(25,list.fold(4){total,next->total+next 1.1.assertEquals(25,list.foldRight(4){total,next->total+next1.1.list.forEach{println(it) listlist.forEachIndexed{index,->println("position$indexcontainsa$value")1.1.assertEquals(6,////TheelementwhosenegativeisassertEquals(1,list.maxBy{-it1.1.assertEquals(1,////TheelementwhosenegativeisassertEquals(6,list.minBy{-it1.1.//Noelementsaredivisibleby2.2.assertTrue(list.none{it%7==0 1.1.assertEquals(21,list.reduce{total,next->total+next 1.1.assertEquals(21,list.reduceRight{total,next->total+next1.1.assertEquals(3,list.sumBy{it%2dropdropWhiledropLastWhilefilterfilterNotfilterNotNullslicetaketakeLasttakeWhile1.1.assertEquals(listOf(5,6),1.1.assertEquals(listOf(3,4,5,6),list.dropWhile{it<31.1.assertEquals(listOf(1,2,3,4),list.dropLastWhile{it>41.1.assertEquals(listOf(2,4,6),list.filter{it%2==01.1.assertEquals(listOf(1,3,5),list.filterNot{it%2==01.1.assertEquals(listOf(1,2,3,4),1.1.assertEquals(listOf(2,4,5),list.slice(listOf(1,3,1.1.assertEquals(listOf(1,2),1.1.assertEquals(listOf(5,6),1.1.assertEquals(listOf(1,2),list.takeWhile{it<3flatMapgroupBymapmapIndexedmapNotNullassertEqualsassertEquals(listOf(1,2,2,3,3,4,4,5,5,6,6,list.flatMap{listOf(it,it+1)1.1.assertEquals(mapOf("odd"tolistOf(1,3,5),"even"tolistOf(2,4,6)),list.groupBy{if(it%2==0)"even"else"odd"})1.1.assertEquals(listOf(2,4,6,8,10,12),list.map{it*21.1.assertEquals(listOf(0,2,6,12,20,30),list.mapIndexed{index,it->index*it})1.1.assertEquals(listOf(2,4,6,8),listWithNull.mapNotNull{it*containselementAtelementAtOrElseelementAtOrNullfirstfirstOrNullindexOfindexOfFirstindexOfLastlastlastIndexOflastOrNullsinglesingleOrNull1.1. 1.1.assertEquals(2,1.1.assertEquals(20,list.elementAtOrElse(10,{2*it1.1.1.1.assertEquals(2,list.first{it%2==01.1.assertNull(list.firstOrNull{it%7==0 1.1.assertEquals(3, 1.1.assertEquals(1,list.indexOfFirst{it%2==0 1.1.assertEquals(5,list.indexOfLast{it%2==01.1.assertEquals(6,list.last{it%2==0 valvallist=listOf(1,2,3,4,5,assertNull(list.lastOrNull{it%7==01.1.assertEquals(5,list.single{it%5==01.1.assertNull(list.singleOrNull{it%7==0mergepartitionpluszipunzipvalvallist=listOf(1,2,3,4,5,vallistRepeated=listOf(2,2,3,4,5,5,assertEquals(listOf(3,4,6,8,10,11),list.merge(listRepeated){it1,it2->it1+it2})

Pair(listOf(2,4,6),listOf(1,3,list.partition{it%2==04. listOf(1,2,3,4,5,6,7,list+listOf(7,4.

listOf(Pair(1,7),Pair(2,list.zip(listOf(7,4.Pair(listOf(5,6),listOf(7,listOf(Pair(5,7),Pair(6,4.reversesortsortBysortDescendingsortDescendingByvalvalunsortedList=listOf(3,2,7,assertEquals(listOf(5,7,2,3),1.1.assertEquals(listOf(2,3,5,7),1.1.assertEquals(listOf(3,7,2,5),unsortedList.sortBy{it%31.1.assertEquals(listOf(7,5,3,2),1.1.assertEquals(listOf(2,5,7,3),unsortedList.sortDescendingBy{%3 創(chuàng)建數(shù)據(jù)庫(kù)創(chuàng)建數(shù)據(jù)庫(kù)model this._id=this.city=this.country=14.classCityForecast(valmap:MutableMap<String,valdailyForecast:List<DayForecast>)var_id:Longbymapvarcity:Stringbymapvarcountry:Stringbyconstructor(id:Long,city:String,country:String,dailyForecast:List<DayForecast>):this(HashMap(),dailyForecast)classclassDayForecast(varmap:MutableMap<String,Any?>)var_id:Longbyvardate:Longbyvardescription:Stringbyvarhigh:Intbyvarlow:IntbyvariconUrl:StringbyvarcityId:Longbyconstructor(date:Long,description:String,high:Int,low:iconUrl:String,cityId::this(HashMap()){this.date=datethis.description=descriptionthis.high=highthis.low=lowthis.iconUrl=iconUrlthis.cityId=cityId查詢一個(gè)forecastdomaindomain

classclass valforecastDbHelper:ForecastDbHelper=valdataMapper:DbDataMapper=DbDataMapper())5.

funrequestForecastByZipCodefunrequestForecastByZipCode(zipCode:Long,date:Long)=forecastDbHelper.use{3.

查詢一個(gè) valvaldailyRequest="${DayForecastTable.CITY_ID}=?""AND${DayForecastTable.DATE}>=valdailyForecast=.whereSimple(dailyRequest,zipCode.toString(),.parseList{DayForecast(HashMap(it))

valvaldailyRequest="${DayForecastTable.CITY_ID}={id}"+${DayForecastTable.DATE}>=valdailyForecast=.where(dailyRequest,"id"tozipCode,"date"to.parseList{DayForecast(HashMap(it))

funfun<T:Any>parser:(Map<String,Any>)->T):List<T>parseList(object:MapRowParser<T> overridefunparseRow(columns:Map<String,Any>):T=5. 1.1.parseList{DayForecast(HashMap(it))databasedatabase

immutablemutableimmutablemutable

valvalcity= .whereSimple("${CityForecastTable.ID}=?",.parseOpt{CityForecast(HashMap(it),dailyForecast) publicpublicfun<T:Any>parser:(Map<String,Any>)->T):T?parseOpt(object:MapRowParser<T> overridefunparseRow(columns:Map<String,Any>):T= domain domain 1.1.if(city!=null)dataMapper.convertToDomain(city)elsefunfunconvertToDomain(forecast:CityForecast)=with(forecast)valdaily=dailyForecast.map{convertDayToDomain(it)ForecastList(_id,city,country,4.privatefunconvertDayToDomain(dayForecast:DayForecast)=with(dayForecast){Forecast(date,description,high,low,8.8.funrequestForecastByZipCodefunrequestForecastByZipCode(zipCode:Long,date:Long)=forecastDbHelper.use{valdailyRequest="${DayForecastTable.CITY_ID}=?AND""${DayForecastTable.DATE}>=valdailyForecast= .whereSimple(dailyRequest,zipCode.toString(),.parseList{DayForecast(HashMap(it))valcity=.whereSimple("${CityForecastTable.ID}=?",.parseOpt{CityForecast(HashMap(it),dailyForecast)if(city!=null)dataMapper.convertToDomain(city)else

保存一個(gè)

funfunsaveForecast(forecast:ForecastList)=forecastDbHelper.use3.

domaindomainfunfunSQLiteDatabase.clear(tableName:String)execSQL("deletefrom3. 3. funfunconvertFromDomain(forecast:ForecastList)=with(forecast)valdaily=dailyForecast.map{convertDayFromDomain(id,it)CityForecast(id,city,country,4.privatefunconvertDayFromDomain(cityId:Long,forecast:with(forecast)DayForecast(date,description,high,low,iconUrl,

Pair<String,Pair<String,

轉(zhuǎn)換成AndroidSDK

1.1.fun<K,V:Any>MutableMap<K,Array<outPair<K,V>>map({Pair(it.key, mapmap

1.insert(CityForecastTable.1.insert(CityForecastTable.NAME,

1.1.dailyForecast.forEach{*it.map.toVarargArray()) funsaveForecast(forecast:ForecastList)=forecastDbHelper.use{with(dataMapper.convertFromDomain(forecast)){insert(CityForecastTable.NAME,*map.toVarargArray())dailyForecastforEach{insert(DayForecastTable.NAME,KotlinKotlin中的null如果你正在使用Java7工作的話,null安全是Kotlin中最令人感興\hForecastForecastforecast= 可可null1.1.vala:Int?=valvala:Int?=5.

valorvalorvalvala:Int?= 至可以使用Elvis valvala:Int?=valmyString=a?.toString()?:

valvalmyString=a?.toString()?:returnvalmyString=a?.toString()?:throw valvala:Int?= 可可null性和JavaJava庫(kù)和AndroidSDK會(huì)發(fā)生什么呢?在Java中,所有對(duì)象可以被

\h\h

\h\h\h \h\h \himportpublicclassNullTestpublicObjectgetObject(){return"";valvaltest=valmyObject:Any= 注解的方式和一些AndrodSDK的知識(shí),我們也很難犯錯(cuò)誤。

overridefunonCreate(savedInstanceState:Bundle?)overridefunonCreate(savedInstanceState:Bundle) 檢查是否存在對(duì)應(yīng)星期的數(shù)據(jù)如果有,返回UI并且渲染

interfaceinterfaceForecastDataSource funrequestForecastByZipCode(zipCode:Long,date:Long):3.zipzip

1.1.classForecastProvider(valsources:List<ForecastDataSource>ForecastProvider.SOURCES)companionobjectvalDAY_IN_MILLIS=1000*60*60*valSOURCES=listOf(ForecastDb(),forecastforecast 1.1.funrequestByZipCode(zipCode:Long,days:Int): =sources.firstResult{requestSource(it,days,zipCode)}1.inline1.inlinefun<T,R:Any>Iterable<T>.firstResult(predicate:(T)-throwNoSuchElementException("Noelementmatchingpredicate

:(elementinvalresult=if(result!=null)return7.

T=R=T=R=

funrequestSourcefunrequestSource(source:ForecastDataSource,days:Int,zipCode:ForecastList? valres=source.requestForecastByZipCode(zipCode,returnif(res!=null&&res.size()>=days)reselse5. 1.1.privatefuntodayTimeSpan()=System.currentTimeMillis()/DAY_IN_MILLIS*DAY_IN_MILLISclassForecastProvider(valsources:List<ForecastDataSource>ForecastProvider.SOURCES)companionobjectvalDAY_IN_MILLIS=1000*60*60*valSOURCES=listOf(ForecastDb(), funrequestByZipCode(zipCode:Long,days:Int): =sources.firstResult{requestSource(it,days,zipCode)}privatefunrequestSource(source:RepositorySource,days:zipCode:Long):ForecastList? valres=source.requestForecastByZipCode(zipCode,returnif(res!=null&&res.size()>=days)reselse privatefuntodayTimeSpan()=System.currentTimeMillis()DAY_IN_MILLIS*20.

classForecastDb(valforecastDbHelper:ForecastDbHelper=ForecastDbHelper.instance,valdataMapper:DbDataMapper=:ForecastDataSourceoverridefunrequestForecastByZipCode(zipCode:Long,forecastDbHelper.use10. classclassForecastServer(valdataMapper:ServerDataMapper= valforecastDb:ForecastDb=ForecastDb()):ForecastDataSource{ overridefunrequestForecastByZipCode(zipCode:Long,date:ForecastList?valresult=valconverted=dataMapper.convertToDomain(zipCode,returnforecastDb.requestForecastByZipCode(zipCode, 11.datadatabasedatadatabase

domain domain domaindomain

RequestForecastCommand(valzipCode:valforecastProvider:ForecastProvider=ForecastProvider()):Command<ForecastList>companionobject{valDAYS=7overridefunexecute():ForecastListreturnforecastProvider.requestByZipCode(zipCode,\hAndroidDevelopersrepository查看相應(yīng)的提交。FlowFlowcontrol和Flowcontrol和Flowcontrol和rangesFlowcontrol和IfIf toast("xisgreaterthan}elsetoast("xequalstoast("xissmallerthan7.1.1.valres=if(x!=null&&x.size()>=days)xelse1.1.valz=if(condition)xelse WhenWhen

whenwhen1->print("x==2->print("x==else->print("I'maprint("xisneither1nor 8. valvalresult=when(x)0,1->else->4.whenwhen(view)isTextView->view.setText("I'maisEditText->toast("EditTextvalue:isViewGroup->toast("Numberof${view.getChildCount()}else->view.visibility=6.valvalcost=when(x)in1..10->in10..100->in100..1000->inspecialValues->"specialelse->"not7. xin1..10->s.contains("hello")->"it'savisViewGroup->"childcount:else->6.ForForforfor(itemincollection)3. forfor(indexin0..viewGroup.getChildCount()-1)valview=view.visibility=4.forfor(iinWhileWhile和do/while while(x>valy=while(ynully在這里是可見(jiàn)的Rangescontrolcontrol

ifif(i>=0&&i<=ifif(iin forfor(iinforfor(iin forfor(iin10downTo

forfor(iin1..4step2)for(iin4downTo1step2) 1.1.for(iin0until4)0until==(i0until==(iin0untilin0..list.size-

1.1.valviews=(0..viewGroup.childCount-1).map{viewGroup.getChildAt(it)}

可以進(jìn)入\hKotlin datadataclassForecast(valid:Long,valdate:Long,valdescription:valhigh:Int,vallow:Int,valiconUrl:

1.1.privatefun<T:Any>requestToSources(f:(ForecastDataSource)->T?):T =sources.firstResult{f(it) funrequestByZipCodefunrequestByZipCode(zipCode:Long,days:Int):ForecastList=requestToSources{valres=it.requestForecastByZipCode(zipCode,if(res!=null&&res.size()>=days)reselsefunrequestForecast(id:Long):Forecast=requestToSources{1.1.funrequestDayForecast(id:Long):overrideoverridefunrequestDayForecast(id:Long):Forecast?=forecastDbHelper.use{valforecast=parseOpt{DayForecast(HashMap(it)) if(forecast!=null)dataMapper.convertDayToDomain(forecast)elsenull5. 1.1.funSelectQueryBuilder.byId(id:Long): =whereSimple("_id=?",

1.1.overridefunrequestDayForecast(id:Long): =throw 是表達(dá)是非常重要的,當(dāng)你使 處理邊界的問(wèn)題或者當(dāng)拋出異常的時(shí)候。

valx=in0..10->in11..20->else->throwvalx=try{doSomething()}catch{nullclassclassvalid: valforecastProvider:ForecastProvider=ForecastProvider()):Command<Forecast>overridefunexecute()=6. 提供一個(gè)新的提供一個(gè)新的提供一個(gè)新的提供一個(gè)新的

forecastforecastpublicpublicclassDetailActivity:AppCompatActivity()companionobjectvalID=valCITY_NAME= 7. \h\htools:text="Few

title=asyncasync valresult=RequestDayForecastCommand(intent.getLongExtra(ID,-1)).execute()uiThread{bindForecast(result)4. importpri

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論