计算机专业外文翻译think in java.docx
《计算机专业外文翻译think in java.docx》由会员分享,可在线阅读,更多相关《计算机专业外文翻译think in java.docx(23页珍藏版)》请在冰豆网上搜索。
![计算机专业外文翻译think in java.docx](https://file1.bdocx.com/fileroot1/2022-10/28/d9094f20-8145-40d6-af7d-bc3856ba1926/d9094f20-8145-40d6-af7d-bc3856ba19261.gif)
计算机专业外文翻译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"),theRationalclassshouldbesmartenoughtorea