




已阅读5页,还剩20页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
0外文原文ThebusyJavadevelopersguidetoScala:ClassactionItmakessenseforJavadeveloperstouseobjectsasafirstpointofreferenceforunderstandingScala.InthissecondinstallmentofThebusyJavadevelopersguidetoScalaseries,TedNewardfollowsabasicpremiseoflanguagemeasurement:thatthepowerofalanguagecanbemeasuredindirectrelationtoitsabilitytointegratenewfacilities-inthiscase,supportforcomplexnumbers.AlongthewayyoullseesomeinterestingtidbitsrelatedtoclassdefinitionsandusageinScala.Inlastmonthsarticle,yousawjustatouchofScalassyntax,thebareminimumnecessarytorunaScalaprogramandobservesomeofitssimplerfeatures.TheHelloWorldandTimerexamplesfromthatarticleletyouseeScalasApplicationclass,itssyntaxformethoddefinitionsandanonymousfunctions,justaglimpseofanArray,andabitontype-inferencing.Scalahasagreatdealmoretooffer,sothisarticleinvestigatestheintricaciesofScalacoding.Scalasfunctionalprogrammingfeaturesarecompelling,buttheyrenottheonlyreasonJavadevelopersshouldbeinterestedinthelanguage.Infact,Scalablendsfunctionalconceptsandobjectorientation.InordertolettheJava-cum-Scalaprogrammerfeelmoreathome,itmakessensetolookatScalasobjectfeaturesandseehowtheymapovertoJavalinguistically.Bearinmindthatthereisntadirectmappingforsomeofthesefeatures,orinsomecases,themappingismoreofananalogthanadirectparallel.Butwherethedistinctionisimportant,Illpointitout.Scalahasclass(es),tooRatherthanembarkonalengthyandabstractdiscussionoftheclassfeaturesthatScalasupports,letslookatadefinitionforaclassthatmightbeusedtobringrationalnumbersupporttotheScalaplatform(largelyswipedfromScalaByExample-seeResources):Listing1.rational.scalaclassRational(n:Int,d:Int)1privatedefgcd(x:Int,y:Int):Int=if(x=0)yelseif(xjavap-private-classpathclassesRationalCompiledfromrational.scalapublicclassRationalextendsjava.lang.Objectimplementsscala.ScalaObjectprivateintdenom;privateintnumer;privateintg;publicRational(int,int);publicRationalunary_$tilde();publicjava.lang.StringtoString();publicRational$div(Rational);publicRational$times(Rational);publicRational$minus(Rational);publicRational$plus(Rational);publicintdenom();publicintnumer();privateintg();privateintgcd(int,int);8publicRational(int);publicint$tag();C:Projectsscala-classescodeTheoperatorsdefinedintheScalaclasstransmogrifyintomethodcallsinthebesttraditionofJavaprogramming,thoughtheydoseemtobebasedonfunnynames.Twoconstructorsaredefinedontheclass:onetakinganintandonetakingapairofints.And,ifyouhappentobeatallconcernedthattheuseoftheupper-caseInttypeissomehowajava.lang.Integerindisguise,notethattheScalacompilerissmartenoughtotransformthemintoregularJavaprimitiveintsintheclassdefinition.Testing,testing,1-2-3.Itisawell-knownmemethatgoodprogrammerswritecode,andgreatprogrammerswritetests;thusfar,IhavebeenlaxinexercisingthisruleformyScalacode,soletsseewhathappenswhenyouputthisRationalclassinsideofatraditionalJUnittestsuite,asshowninListing10:Listing10.RationalTest.javaimportorg.junit.*;importstaticorg.junit.Assert.*;publicclassRationalTestTestpublicvoidtest2ArgRationalConstructor()Rationalr=newRational(2,5);assertTrue(r.numer()=2);assertTrue(r.denom()=5);Testpublicvoidtest1ArgRationalConstructor()9Rationalr=newRational(5);assertTrue(r.numer()=0);assertTrue(r.denom()=1);/1becauseofgcd()invocationduringconstruction;/0-over-5isthesameas0-over-1TestpublicvoidtestAddRationals()Rationalr1=newRational(2,5);Rationalr2=newRational(1,3);Rationalr3=(Rational)reflectInvoke(r1,$plus,r2);/r1.$plus(r2);assertTrue(r3.numer()=11);assertTrue(r3.denom()=15);/.somedetailsomittedAsidefromconfirmingthattheRationalclassbehaves,well,rationally,theabovetestsuitealsoprovesthatitispossibletocallScalacodefromJavacode(albeitwithalittlebitofanimpedancemismatchwhenitcomestotheoperators).Thecoolthingaboutthis,ofcourse,isthatitletsyoutryoutScalaslowly,bymigratingJavaclassesovertoScalaclasseswithouteverhavingtochangetheteststhatbackthem.Theonlyweirdnessyoumightnoticeinthetestcodehastodowithoperatorinvocation,inthiscase,the+methodontheRationalclass.Lookingbackatthejavapoutput,Scalahasobviouslytranslatedthe+functionintotheJVMmethod$plus,buttheJavaLanguageSpecificationdoesnotallowthe$characterinidentifiers(whichiswhyitsusedinnestedandanonymousnestedclassnames).10Inordertoinvokethosemethods,youeitherhavetowritethetestsinGroovyorJRuby(orsomeotherlanguagethatdoesntposearestrictiononthe$character),oryoucanwritealittlebitofReflectioncodetoinvokeit.Igowiththelatterapproach,whichisntallthatinterestingfromaScalaperspective,buttheresultisincludedinthisarticlescodebundle,shouldyoubecurious.(SeeDownload.)NotethatworkaroundsliketheseareonlynecessaryforfunctionnamesthatarentalsolegitimateJavaidentifiers.AbetterJavaBackwhenIwasfirstlearningC+,BjarneStroustrupsuggestedthatonewaytolearnC+wastoseeitasabetterC(seeResources).Insomeways,JavadeveloperstodaymightcometoseeScalaasabetterJava,becauseitprovidesamoreterseandsuccinctwayofwritingtraditionalJavaPOJOs.ConsiderthetraditionalPersonPOJOshowninListing11:Listing11.JavaPerson.java(originalPOJO)publicclassJavaPersonpublicJavaPerson(StringfirstName,StringlastName,intage)this.firstName=firstName;this.lastName=lastName;this.age=age;publicStringgetFirstName()returnthis.firstName;publicvoidsetFirstName(Stringvalue)11this.firstName=value;publicStringgetLastName()returnthis.lastName;publicvoidsetLastName(Stringvalue)this.lastName=value;publicintgetAge()returnthis.age;publicvoidsetAge(intvalue)this.age=value;publicStringtoString()returnPerson:firstName+firstName+lastName:+lastName+age:+age+;privateStringfirstName;privateStringlastName;privateintage;12NowconsideritsequivalentwritteninScala:Listing12.person.scala(threadsafePOJO)classPerson(firstName:String,lastName:String,age:Int)defgetFirstName=firstNamedefgetLastName=lastNamedefgetAge=ageoverridedeftoString=PersonfirstName:+firstName+lastName:+lastName+age:+age+Itisntacompletedrop-inreplacement,giventhattheoriginalPersonhadsomemutablesetters.ButconsideringtheoriginalPersonalsohadnosynchronizationcodearoundthosemutablesetters,theScalaversionissafertouse.Also,ifthegoalistotrulyreducethenumberoflinesofcodeinPerson,youcouldremovethegetFoopropertymethodsentirelybecauseScalawillgenerateaccessormethodsaroundeachoftheconstructorparameters-firstName()returnsaString,lastName()returnsaString,andage()returnsanint).Eveniftheneedforthosemutablesettermethodsisundeniable,theScalaversionisstillsimpler,asyoucanseeinListing13:Listing13.person.scala(fullPOJO)classPerson(varfirstName:String,varlastName:String,varage:Int)defgetFirstName=firstNamedefgetLastName=lastNamedefgetAge=agedefsetFirstName(value:String):Unit=firstName=valuedefsetLastName(value:String)=lastName=value13defsetAge(value:Int)=age=valueoverridedeftoString=PersonfirstName:+firstName+lastName:+lastName+age:+age+Asanaside,noticetheintroductionofthevarkeywordontheconstructorparameters.Withoutgoingintotoomuchdetail,vartellsthecompilerthatthevalueismutable.Asaresult,Scalageneratesbothaccessor(StringfirstName(void)andmutator(voidfirstName_$eq(String)methods.ItthenbecomeseasytocreatesetFoopropertymutatormethodsthatusethegeneratedmutatormethodsunderthehood.ConclusionScalaisanattempttoincorporatefunctionalconceptsandtersenesswithoutlosingtherichnessoftheobjectparadigm.Asyouveperhapsbeguntoseeinthisseries,Scalaalsocorrectssomeoftheegregious(inhindsight)syntacticproblemsfoundintheJavalanguage.ThissecondarticleintheBusyJavadevelopersguidetoScalaserieshasfocusedonScalasobjectfacilities,whichletyoustartusingScalawithouthavingtodivetoodeeplyintothefunctionalpool.Basedonwhatyouvelearnedsofar,youcanalreadystartusingScalatoreduceyourprogrammingworkload.Amongotherthings,youcanuseScalatoproducetheverysamePOJOsneededforotherprogrammingenvironments,suchasSpringorHibernate.Holdontoyourdivingcapsandscubagear,however,becausenextmonthsarticlewillmarkthebeginningofourdescentintothedeependofthefunctionalpool.14外文翻译面向Java开发人员的Scala指南:类操作Java开发人员可以将对象作为理解Scala的出发点。本文是面向Java开发人员的Scala指南系列的第二期,作者TedNeward遵循对一种语言进行评价的基本前提:一种语言的威力可以直接通过它集成新功能的能力衡量,在本文中就是指对复数的支持。跟随本文,您将了解在Scala中与类的定义和使用有关的一些有趣特性。在上一期文章中,您只是稍微了解了一些Scala语法,这些是运行Scala程序和了解其简单特性的最基本要求。通过上一篇文章中的HelloWorld和Timer示例程序,您了解了Scala的Application类、方法定义和匿名函数的语法,还稍微了解Array和一些类型推断方面的知识。Scala还提供了很多其他特性,本文将研究Scala编程中的一些较复杂方面。Scala的函数编程特性非常引人注目,但这并非Java开发人员应该对这门语言感兴趣的惟一原因。实际上,Scala融合了函数概念和面向对象概念。为了让Java和Scala程序员感到得心应手,可以了解一下Scala的对象特性,看看它们是如何在语言方面与Java对应的。记住,其中的一些特性并不是直接对应,或者说,在某些情况下,“对应”更像是一种类比,而不是直接的对应。不过,遇到重要区别时,我会指出来。Scala和Java一样使用类我们不对Scala支持的类特性作冗长而抽象的讨论,而是着眼于一个类的定义,这个类可用于为Scala平台引入对有理数的支持(主要借鉴自“ScalaByExample”,参见参考资料):清单1.Rational.scalaclassRational(n:Int,d:Int)privatedefgcd(x:Int,y:Int):Int=if(x=0)yelseif(xjavap-private-classpathclassesRational19Compiledfromrational.scalapublicclassRationalextendsjava.lang.Objectimplementsscala.ScalaObjectprivateintdenom;privateintnumer;privateintg;publicRational(int,int);publicRationalunary_$tilde();publicjava.lang.StringtoString();publicRational$div(Rational);publicRational$times(Rational);publicRational$minus(Rational);publicRational$plus(Rational);publicintdenom();publicintnumer();privateintg();privateintgcd(int,int);publicRational(int);publicint$tag();C:Projectsscala-classescodeScala类中定义的“操作符”被转换成传统Java编程中的方法调用,不过它们仍使用看上去有些古怪的名称。类中定义了两个构造函数:一个构造函数带有一个int参数,另一个带有两个int参数。您可能会注意到,大写的Int类型与java.lang.Integer有点相似,Scala编译器非常聪明,会在类定义中将它们转换成常规的Java原语int。测试Rational类一种著名的观点认为,优秀的程序员编写代码,伟大的程序员编写测试;到目前为止,我还没有对我的Scala代码严格地实践这一规则,那么现在看看将这个Rational类放入一个传统的JUnit测试套件中会怎样,如清单10所示:清单10.RationalTest.javaimportorg.junit.*;20importstaticorg.junit.Assert.*;publicclassRationalTestTestpublicvoidtest2ArgRationalConstructor()Rationalr=newRational(2,5);assertTrue(r.numer()=2);assertTrue(r.denom()=5);Testpublicvoidtest1ArgRationalConstructor()Rationalr=newRational(5);assertTrue(r.numer()=0);assertTrue(r.denom()=1);/1becauseofgcd()invocationduringconstruction;/0-over-5isthesameas0-over-1TestpublicvoidtestAddRationals()Rationalr1=newRational(2,5);Rationalr2=newRational(1,3);Rationalr3=(Rational)reflectInvoke(r1,$plus,r2);/r1.$plus(r2);assertTrue(r3.numer()=11);assertTrue(r3.denom()=15);/.somedetailsomitted21除了确认Rational类运行正常之外,上面的测试套件还证明可以从Java代码中调用Scala代码(尽管在操作符方面有点不匹配)。当然,令人高兴的是,您可以将Java类迁移至Scala类,同时不必更改支持这些类的测试,然后慢慢尝试Scala。您惟一可能觉得古怪的地方是操作符调用,在本例中就是Rational类中的+方法。回顾一下javap的输出,Scala显然已经将+函数转换为JVM方法$plus,但是Java语言规范并不允许标识符中出现$字符(这正是它被用于嵌套和匿名嵌套类名称中的原因)。为了调用那些方法,需要用Groovy或JRuby(或者其他对$字符没有限制的语言)编写测试,或者编写Reflection代码来调用它。我采用后一种方法,从Scala的角度看这不是那么有趣,但是如果您有兴趣的话,可以看看本文的代码中包含的结果(参见下载)。注意,只有当函数名称不是合法的Java标识符时才需要用这类方法。“更好的”Java我学习C+的时候BjarneStroustrup建议,学习C+的一种方法是将它看作“更好的C语言”(参见参考资料)。在某些方面,如今的Java开发人员也可以将Scala看作是“更好的Java”,因为它提供了一种编写传统JavaPOJO的更简洁的方式。考虑清单11中显示的传统PersonPOJO:清单11.JavaPerson.java(原始POJO)publicclassJavaPersonpublicJavaPerson(StringfirstName,StringlastName,intage)this.firstName=firstName;this.lastName=lastName;this.age=age;publicStringgetFirstName()returnthis.firstName;publicvoidsetFirstName(Stringvalue)this.firstName=value;22publicStringgetLastName()returnthis.lastName;publicvoidsetLastName(Stringvalue)this.lastName=value;publicintgetAge()returnthis.age;publicvoidsetAge(intvalue)this.age=value;publicStringtoString()returnPerson:firstName+firstName+lastName:+lastName+age:+age+;privateStringfirstName;privateStringlastName;privateintage;现在考虑用Scala编写的对等物:清单12.person.scala(
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025年度泵站设备维修保养与技术支持服务合同
- 2025版土地收购与安置补偿协议
- 2025版新材料研发合作协议
- 2025年度文化旅游项目投标标前合作合同
- 2025版跨境电商贸易生意合同范本
- 2025年二手房交易全程跟踪与独家代理服务合同
- 2025版设备购置与借款综合服务协议
- 2025宾馆餐厅特色早餐承包与供应服务合同
- 2025年数字货币对金融行业数字化转型中的数据安全与隐私保护策略研究与应用前景分析报告
- 2025年二手房存量房市场推广及广告投放合同
- 超声波龈下刮治术专题讲解
- 2025年电信传输工程师职称考试试题
- 小学一年级升二年级暑假数学作业-58套计算
- 2025年思想政治理论知识测试与能力考试试题及答案
- 福利院消防培训课件
- 肩袖修复术后影像学评估的新技术
- 未成年人违法犯罪警示教育
- 医疗废物与污水处理培训
- 4S店员工职业卫生培训
- 体检机构礼仪培训
- 《工业机器人技术与应用》高职人工智能技术应用专业全套教学课件
评论
0/150
提交评论