计算机专业外文翻译thinkinjava.docx

上传人:b****3 文档编号:10215705 上传时间:2023-05-24 格式:DOCX 页数:27 大小:31.43KB
下载 相关 举报
计算机专业外文翻译thinkinjava.docx_第1页
第1页 / 共27页
计算机专业外文翻译thinkinjava.docx_第2页
第2页 / 共27页
计算机专业外文翻译thinkinjava.docx_第3页
第3页 / 共27页
计算机专业外文翻译thinkinjava.docx_第4页
第4页 / 共27页
计算机专业外文翻译thinkinjava.docx_第5页
第5页 / 共27页
计算机专业外文翻译thinkinjava.docx_第6页
第6页 / 共27页
计算机专业外文翻译thinkinjava.docx_第7页
第7页 / 共27页
计算机专业外文翻译thinkinjava.docx_第8页
第8页 / 共27页
计算机专业外文翻译thinkinjava.docx_第9页
第9页 / 共27页
计算机专业外文翻译thinkinjava.docx_第10页
第10页 / 共27页
计算机专业外文翻译thinkinjava.docx_第11页
第11页 / 共27页
计算机专业外文翻译thinkinjava.docx_第12页
第12页 / 共27页
计算机专业外文翻译thinkinjava.docx_第13页
第13页 / 共27页
计算机专业外文翻译thinkinjava.docx_第14页
第14页 / 共27页
计算机专业外文翻译thinkinjava.docx_第15页
第15页 / 共27页
计算机专业外文翻译thinkinjava.docx_第16页
第16页 / 共27页
计算机专业外文翻译thinkinjava.docx_第17页
第17页 / 共27页
计算机专业外文翻译thinkinjava.docx_第18页
第18页 / 共27页
计算机专业外文翻译thinkinjava.docx_第19页
第19页 / 共27页
计算机专业外文翻译thinkinjava.docx_第20页
第20页 / 共27页
亲,该文档总共27页,到这儿已超出免费预览范围,如果喜欢就下载吧!
下载资源
资源描述

计算机专业外文翻译thinkinjava.docx

《计算机专业外文翻译thinkinjava.docx》由会员分享,可在线阅读,更多相关《计算机专业外文翻译thinkinjava.docx(27页珍藏版)》请在冰点文库上搜索。

计算机专业外文翻译thinkinjava.docx

计算机专业外文翻译thinkinjava

来自:

thinkinjava(3)

外文原文

ThebusyJavadeveloper'sguidetoScala:

Classaction

ItmakessenseforJava™developerstouseobjectsasafirstpointofreferenceforunderstandingScala.InthissecondinstallmentofThebusyJavadeveloper'sguidetoScalaseries,TedNewardfollowsabasicpremiseoflanguagemeasurement:

thatthepowerofalanguagecanbemeasuredindirectrelationtoitsabilitytointegratenewfacilities--inthiscase,supportforcomplexnumbers.Alongthewayyou'llseesomeinterestingtidbitsrelatedtoclassdefinitionsandusageinScala.Inlastmonth'sarticle,yousawjustatouchofScala'ssyntax,thebareminimumnecessarytorunaScalaprogramandobservesomeofitssimplerfeatures.TheHelloWorldandTimerexamplesfromthatarticleletyouseeScala'sApplicationclass,itssyntaxformethoddefinitionsandanonymousfunctions,justaglimpseofanArray[],andabitontype-inferencing.Scalahasagreatdealmoretooffer,sothisarticleinvestigatestheintricaciesofScalacoding.

Scala'sfunctionalprogrammingfeaturesarecompelling,butthey'renottheonlyreasonJavadevelopersshouldbeinterestedinthelanguage.Infact,Scalablendsfunctionalconceptsandobjectorientation.InordertolettheJava-cum-Scalaprogrammerfeelmoreathome,itmakessensetolookatScala'sobjectfeaturesandseehowtheymapovertoJavalinguistically.Bearinmindthatthereisn'tadirectmappingforsomeofthesefeatures,orinsomecases,the"mapping"ismoreofananalogthanadirectparallel.Butwherethedistinctionisimportant,I'llpointitout.

Scalahasclass(es),too

RatherthanembarkonalengthyandabstractdiscussionoftheclassfeaturesthatScalasupports,let'slookatadefinitionforaclassthatmightbeusedtobringrationalnumbersupporttotheScalaplatform(largelyswipedfrom"ScalaByExample"--seeResources):

Listing1.rational.scala

classRational(n:

Int,d:

Int)

{

privatedefgcd(x:

Int,y:

Int):

Int=

{

if(x==0)y

elseif(x<0)gcd(-x,y)

elseif(y<0)-gcd(x,-y)

elsegcd(y%x,x)

}

privatevalg=gcd(n,d)

valnumer:

Int=n/g

valdenom:

Int=d/g

def+(that:

Rational)=

newRational(numer*that.denom+that.numer*denom,denom*that.denom)

def-(that:

Rational)=

newRational(numer*that.denom-that.numer*denom,denom*that.denom)

def*(that:

Rational)=

newRational(numer*that.numer,denom*that.denom)

def/(that:

Rational)=

newRational(numer*that.denom,denom*that.numer)

overridedeftoString()=

"Rational:

["+numer+"/"+denom+"]"

}

WhiletheoverallstructureofListing1islexicallysimilartowhatyou'veseeninJavacodeoverthelastdecade,somenewelementsclearlyareatworkhere.Beforepickingthisdefinitionapart,takealookatthecodetoexercisethenewRationalclass:

Listing2.RunRational

classRational(n:

Int,d:

Int)

{

//...asbefore

}

objectRunRationalextendsApplication

{

valr1=newRational(1,3)

valr2=newRational(2,5)

valr3=r1-r2

valr4=r1+r2

Console.println("r1="+r1)

Console.println("r2="+r2)

Console.println("r3=r1-r2="+r3)

Console.println("r4=r1+r2="+r4)

}

WhatyouseeinListing2isn'tterriblyexciting:

Icreateacoupleofrationalnumbers,createtwomoreRationalsastheadditionandsubtractionofthefirsttwo,andechoeverythingtotheconsole.(NotethatConsole.println()comesfromtheScalacorelibrary,livinginscala.*,andisimplicitlyimportedintoeveryScalaprogram,justasjava.langisinJavaprogramming.)

HowmanywaysshallIconstructthee?

NowlookagainatthefirstlineintheRationalclassdefinition:

Listing3.Scala'sdefaultconstructor

classRational(n:

Int,d:

Int)

{

//...

Althoughyoumightthinkyou'relookingatsomekindofgenerics-likesyntaxinListing3,it'sactuallythedefaultandpreferredconstructorfortheRationalclass:

nanddaresimplytheparameterstothatconstructor.

Scala'spreferenceforasingleconstructormakesacertainkindofsense--mostclassesenduphavingasingleconstructororacollectionofconstructorsthatall"chain"throughasingleconstructorasaconvenience.Ifyouwantedto,youcoulddefinemoreconstructorsonaRationallikeso:

Listing4.Achainofconstructors

classRational(n:

Int,d:

Int)

{

defthis(d:

Int)={this(0,d)}

NotethatScala'sconstructorchaindoestheusualJava-constructor-chainingthingbycallingintothepreferredconstructor(theInt,Intversion).

Details,(implementation)details...

Whenworkingwithrationalnumbers,ithelpstoperformabitofnumericallegerdemain:

namelythatoffindingacommondenominatortomakecertainoperationseasier.Ifyouwanttoadd1-over-2(alsoknownas"one-half")to2-over-4(alsoknownas"two-fourths"),theRationalclassshouldbesmartenoughtorealizethat2-over-4isthesameas1-over-2,andconvertitaccordinglybeforeaddingthetwotogether.

Thisisthepurposeofthenestedprivategcd()functionandgvalueinsideoftheRationalclass.WhentheconstructorisinvokedinScala,theentirebodyoftheclassisevaluated,whichmeansgwillbeinitializedwiththegreatestcommondenominatorofnandd,andthenusedinturntosetnanddappropriately.

LookingbackatListing1,it'salsofairlyeasytoseethatIcreatedanoverriddentoStringmethodtoreturnthevaluesofRational,whichwillbeveryusefulwhenIstartexercisingitfromtheRunRationaldrivercode.

NoticethesyntaxaroundtoString,however:

theoverridekeywordinthefrontofthedefinitionisrequiredsothatScalacanchecktomakesurethatacorrespondingdefinitionexistsinthebaseclass.Thiscanhelppreventsubtlebugscreatedbyaccidentalkeyboardslips.(Itwasthissamemotivationthatledtothecreationofthe@OverrideannotationinJava5.)Notice,aswell,thatthereturntypeisnotspecified--it'sobviousfromthedefinitionofthemethodbody--andthatthereturnedvalueisn'texplicitlydenotedusingthereturnkeyword,whichJavawouldrequire.Instead,thelastvalueinthefunctionisconsideredthereturnvalueimplicitly.(YoucanalwaysusereturnkeywordifyoupreferJavasyntax,however.)

Somecorevalues

Nextuparethedefinitionsofnumeranddenom,respectively.Thesyntaxinvolved,offhand,wouldleadtheJavaprogrammertobelievethatnumeranddenomarepublicIntfieldsthatareinitializedtothevalueofn-over-gandd-over-g,respectively;butthisassumptionisincorrect.

Formally,Scalacallsnumeranddenommethodswithoutparameters,whichareusedtocreateaquick-and-easysyntaxfordefiningaccessors.TheRationalclassstillhasthreeprivatefields,n,d,andg,buttheyarehiddenfromtheworldbydefaultprivateaccessinthecaseofnandd,andbyexplicitprivateaccessinthecaseofg.

TheJavaprogrammerinyouisprobablyaskingatthispoint,"Wherearethecorresponding"setters"fornandd?

"Nosuchsettersexist.PartofthepowerofScalaisthatitencouragesdeveloperstocreateimmutableobjectsbydefault.Granted,syntaxisavailabletocreatemethodsformodifyingtheinternalsofRational,butdoingsowouldruintheimplicitthread-safenatureofthisclass.Asaresult,atleastforthisexample,I'mgoingtoleaveRationalasitis.

Naturally,thatraisesthequestionofhowonemanipulatesaRational.Likejava.lang.Strings,youcan'ttakeanexistingRationalandmodifyitsvalues,sotheonlyalternativeistocreatenewRationalsoutofthevaluesofanexistingone,orcreateitfromscratch.Thisbringsintofocusthenextsetoffourmethods:

thecuriouslynamed+,-,*,and/methods.

Andno,contrarytowhatitmightlooklike,thisisn'toperator-overloading.

Operator,ringmeanumber

RememberthatinScalaeverythingisanobject.Inthelastarticle,yousawhowthatprincipleappliestotheideathatfunctionsthemselvesareobjects,whichallowsScalaprogrammerstoassignfunctionstovariables,passfunctionsasobjectparameters,andsoon.Anequallyimportantprincipleisthateverythingisafunction;thatistosay,inthisparticularcase,thereisnodistinctionbetweenafunctionnamedaddandafunctionnamed+.InScala,alloperatorsarefunctionsonaclass.Theyjusthappentohave,well,funkynames.

IntheRationalclass,then,fouroperationshavebeendefinedforrationalnumbers.Thesearethecanonical,mathematicaloperationsadd,subtract,multiply,anddivide.Eachoftheseisnamedbyitsmathematicalsymbol:

+,-,*,and/.

Notice,however,thateachoftheseoperatorsworksbyconstructinganewRationalobjecteachtime.Again,thisisverysimilartohowjava.lang.Stringworks,anditisthedefaultimplementationbecauseityieldsthread-safecode.(Ifnosharedstate--andinternalstateofanobjectsharedacrossthreadsisimplicitlysharedstate--ismodifiedbyathread,thenthereisnoconcernoverconcurrentaccesstothatstate.)

What'snewwithyou?

Theeverythingisafunctionrulehastwopowerfuleffects:

Thefirst,asyou'vealreadyseen,isthatfunctionscanbemanipulatedandstoredasobjectsthemselves.Thisleadstopowerfulre-usescenariosliketheoneexploredinthefirstarticleinthisseries.

ThesecondeffectisthatthereisnospecialdistinctionbetweentheoperatorsthattheScala-languagedesignersmightthinktoprovideandtheoperatorsthatScalaprogrammersthinkshouldbeprovided.Forexample,let'sassumeforamomentthatitmakessensetoprovidean"inversion"operator,whichwillflipthenumeratoranddenominatorandreturnanewRational(sothatRational(2,5)willreturnRational(5,2)).Ifyoudecidethatthe~symbolbestrepresentsthisconcept,thenyoucandefineanewmetho

展开阅读全文
相关资源
猜你喜欢
相关搜索
资源标签

当前位置:首页 > 总结汇报 > 学习总结

copyright@ 2008-2023 冰点文库 网站版权所有

经营许可证编号:鄂ICP备19020893号-2