Tải bản đầy đủ (.pdf) (159 trang)

Leanpub learn scala for java developers

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (2.86 MB, 159 trang )


LearnScalaforJavaDevelopers

TobyWeston

Thisbookisforsaleat />Thisversionwaspublishedon2015-04-21

*****
ThisisaLeanpubbook.LeanpubempowersauthorsandpublisherswiththeLean
Publishingprocess.LeanPublishingistheactofpublishinganin-progressebookusing
lightweighttoolsandmanyiterationstogetreaderfeedback,pivotuntilyouhavetheright
bookandbuildtractiononceyoudo.
*****
©2015TobyWeston


TableofContents
Preface

I.ScalaTour
TheScalaLanguage
PureFunctions
Higher-OrderFunctions
Scala’sBackground
TheFuture

InstallingScala
TheScalaInterpreter
ScalaScripts
scalac


SomeBasicSyntax
DefiningValuesandVariables
DefiningFunctions
OperatorOverloadingandInfixNotation
Collections
JavaInteroperability
PrimitiveTypes

Scala’sClassHierarchy
AnyVal
Unit
AnyRef

BottomTypes

ScalaDoc
LanguageFeatures
WorkingwithSourceCode
WorkingwithMethods
FunctionalProgramming

Summary

II.KeySyntacticalDifferences
ClassesandFields
CreatingClasses
DerivedSettersandGetters
RedefiningSettersandGetters
Summary


ClassesandObjects
ClassesWithoutConstructorArguments
AdditionalConstructors
SingletonObjects
CompanionObjects

Inheritance
SubtypeInheritance
AnonymousClasses
Interfaces/Traits
AbstractClasses
Polymorphism


DecidingBetweentheOptions

ControlStructures
Conditionals
LoopingStructures;do,whileandfor
BreakingControlFlow(breakandcontinue)
Exceptions

Generics
ParametricPolymorphism
BoundedClasses
Variance

III.BeyondJavatoScala
FakingFunctionCalls
TheapplyMethod

TheupdateMethod
Summary

FakingLanguageConstructs
CurlyBraces(andFunctionLiterals)
Currying
Summary

PatternMatching
Switching
Patterns
LiteralMatches
ConstructorMatches
TypeQuery
DeconstructionMatchesandunapply
GuardConditions

MapandFlatMap
MappingFunctions
FlatMap
NotJustforCollections

Monads
BasicDefinition
Option
MoreFormalDefinition
Summary

ForComprehensions
WhereWeLeftOff

UsingNullChecks
UsingflatMapwithOption
HowForComprehensionsWork
Finally,UsingaForComprehensionforShippingLabels
Summary

IV.AdoptingScalainJavaTeams
AdoptingScala
AvoidNotEnough
Don’tDoTooMuch
PurelyFunctionalFTW?

WhattoExpect
TheLearningCurve
TheLearningContinuum


Tips
BeClear
GetGuidance
HaveaPlan

ConvertYourCodebase
ManageYourCodebase
Conventions
WhattoAvoid
OtherChallenges

SyntaxCheatSheet
Index



Preface
Audience
ThisbookisforJavadeveloperslookingtotransitiontoprogramminginScala.
AbouttheAuthor
TobyWestonisanindependentsoftwaredeveloperbasedinLondon.Hespecialisesin
JavaandScaladevelopment,workinginagileenvironments.He’sakeenbloggerand
writer,havingwrittenforJAXenterandauthoredthebooksEssentialAcceptanceTesting
andWhat’sNewinJava8.Abigsupporterofopensourcesoftware,Tobyhascontributed
toseveralprojectsincludingjMock.
TheStructureoftheBook
Thebookissplitintofourparts:atourofScala,acomparisonbetweenJavaandScala,
Scala-specificfeaturesandfunctionalprogrammingidioms,andfinallyadiscussionabout
adoptingScalaintoexistingJavateams.
Inthefirstpart,we’regoingtotakeahigh-leveltourofScala.You’llgetafeelforthe
language’sconstructsandhowScalaissimilarinalotofwaystoJava,yetverydifferent
inothers.We’lltakealookatinstallingScalaandusingtheinteractiveinterpreterand
we’llgothroughsomebasicsyntaxexamples.
PartII.talksaboutkeydifferencesbetweenJavaandScala.We’lllookatwhat’smissing
inScalacomparedtoJavaandhowconceptstranslatefromonelanguagetoanother.
TheninPartIII.,we’lltalkaboutsomeofthelanguagefeaturesthatScalaoffersthat
aren’tfoundinJava.Thissectionalsotalksalittleaboutfunctionalprogrammingidioms.
Finally,we’lltalkaboutadoptingScalaintolegacyJavaprojectsandteams.It’snot
alwaysaneasytransition,sowe’lllookatwhyyouwouldwantto,andsomeofthe
challengesyoumightface.
Credits
AuthorTobyWeston()
CopyeditorAmyBrown()



I.SCALATOUR
WelcometoLearnScalaforJavaDevelopers.Thisbookwillhelpyoutransitionfrom
programminginJavatoprogramminginScala.It’sdesignedtohelpJavadevelopersget
startedwithScalawithoutnecessarilyadoptingallofthemoreadvancedfunctional
programmingidioms.
Scalaisbothanobject-orientedlanguageandafunctionallanguageandalthoughIdotalk
aboutsomeoftheadvantagesoffunctionalprogramming,thisbookismoreaboutbeing
productivewithimperativeScalathangettingtogripswithfunctionalprogramming.If
you’realreadyfamiliarwithScalabutarelookingtomaketheleaptopurefunctional
programming,thisprobablyisn’tthebookforyou.CheckouttheexcellentFunctional
ProgramminginScalabyPaulChiusanoandRúnarBjarnasoinstead.
Thebookoftencompares“like-for-like”betweenJavaandScala.So,ifyou’refamiliar
withdoingsomethingaparticularwayinJava,I’llshowhowyoumightdothesamething
inScala.Alongtheway,I’llintroducetheScalalanguagesyntax.



TheScalaLanguage
Scalaisbothafunctionalprogramminglanguageandanobject-orientedprogramming
language.AsaJavaprogrammer,you’llbecomfortablewiththeobject-oriented
definition:Scalahasclasses,objects,inheritance,composition,polymorphism—allthe
thingsyou’reusedtoinJava.
Infact,ScalagoessomewhatfurtherthanJava.Thereareno“non”-objects.Everythingis
anobject,sotherearenoprimitivetypeslikeintandnostaticmethodsorfields.
Functionsareobjectsandevenvaluesareobjects.
Scalacanbeaccuratelydescribedasafunctionalprogramminglanguagebecauseitmeets
somefairlyformalcriteria.Forexample,itallowsyoubothtodefinepurefunctionsand
usehigher-orderfunctions.


PureFunctions
Purefunctionsaren’tassociatedwithobjects,andworkwithoutsideeffects.Akey
concerninScalaprogrammingisavoidingmutation.There’sevenakeywordtodefinea
fixedvariable,alittlelikeJava’sfinal:val.
Purefunctionsshouldoperatebytransformationratherthanmutation.Thatistosay,a
purefunctionshouldtakeargumentsandreturnresultsbutnotmodifytheenvironmentit
operatesin.Thispurityoffunctioniswhatenablesreferentialtransparency.


Higher-OrderFunctions
Functionallanguagesshouldtreatfunctionsasfirst-classcitizens.Thismeanstheysupport
higher-orderfunctions:functionsthattakefunctionsasargumentsorreturnfunctionsand
allowfunctionstobestoredforlaterexecution.Thisisapowerfultechniqueinfunctional
programming.

Scala’sBackground
Scalastartedlifein2003asaresearchprojectatEPFLinSwitzerland.Theprojectwas
headedbyMartinOdersky,who’dpreviouslyworkedonJavagenericsandtheJava
compilerforSunMicrosystems.
It’squiterareforanacademiclanguagetocrossoverintoindustry,butOderskyandothers
launchedTypesafeInc.,acommercialenterprisebuiltaroundScala.Sincethen,Scalahas
movedintothemainstreamasadevelopmentlanguage.
ScalaoffersamoreconcisesyntaxthanJavabutrunsontheJVM.RunningontheJVM
should(intheory)meananeasymigrationtoproductionenvironments;ifyoualready
havetheOracleJVMinstalledinyourproductionenvironment,itmakesnodifferenceif
thebytecodewasgeneratedfromtheJavaorScalacompiler.
ItalsomeansthatScalahasJavainteroperabilitybuiltin,whichinturnmeansthatScala
canuseanyJavalibrary.OneofJava’sstrengthsoveritscompetitorswasalwaysthehuge
numberofopensourcelibrariesandtoolsavailable.Theseareprettymuchallavailableto
Scalatoo.TheScalacommunityhasthatsameopensourcementality,andsothere’sa

growingnumberofexcellentScalalibrariesoutthere.

TheFuture
Scalahasdefinitelymovedintothemainstreamasapopularlanguage.Ithasbeenadopted
bylotsofbigcompaniesincludingTwitter,eBay,Yahoo,HSBC,UBS,andMorgan
Stanley,andit’sunlikelytofalloutoffavouranytimesoon.Ifyou’renervousaboutusing
itinproduction,don’tbe;it’sbackedbyaninternationalorganisationandregularlyscores
wellinpopularityindexes.
ThetoolingisstillbehindJavathough.PowerfulIDEslikeIntelliJ’sIDEAandEclipse
makerefactoringJavacodestraightforwardbutaren’tquitethereyetforScala.Thesame
istrueofcompiletimes:ScalaisalotslowertocompilethanJava.Thesethingswill
improveovertime,andonbalance,they’renotthebiggesthindrancesIencounterwhen
developing.


InstallingScala
ThereareacoupleofwaystogetstartedwithScala.
1. YoucanrunScalainteractivelywiththeinterpreter,
2. runshorterprogramsasshellscripts,or
3. compileprogramswiththescalaccompiler.

TheScalaInterpreter
BeforeworkingwithanIDE,it’sprobablyworthgettingfamiliarwiththeScala
interpreter,orREPL.
DownloadthelatestScalabinaries(fromandextractthe
archive.AssumingyouhaveJavainstalled,youcanstartusingtheinterpreterfroma
commandpromptorterminalwindowstraightaway.Tostartuptheinterpreter,navigateto
theexplodedfolderandtype1:
bin/scala


You’llbefacedwiththeScalaprompt.
scala>_

Youcantypecommandsfollowedbyenter,andtheinterpreterwillevaluatethe
expressionandprinttheresult.Itreads,evaluatesandprintsinaloopsoit’sknownasa
REPL.


Ifyoutype42*4andhitenter,theREPLevaluatestheinputanddisplaystheresult.
scala>42*4
res0:Int=168

Inthiscase,theresultisassignedtoavariablecalledres0.Youcangoontousethis,for
exampletogethalfofres0.
scala>res0/2
res1:Int=84

Thenewresultisassignedtores1.
NoticetheREPLalsodisplaysthetypeoftheresult:res0andres1arebothintegers
(Int).Scalahasinferredthetypesbasedonthevalues.
Ifyouaddres1totheendofastring,noproblem;thenewresultobjectisastring.
scala>"HelloPrisoner"+res1
res2:String=HelloPrisoner84

ToquittheREPL,type:
:quit

ScalaScripts
ThecreatorsofScalaoriginallytriedtopromotetheuseofScalafromUnixshellscripts.
AscompetitiontoPerl,GroovyorbashscriptsonUnixenvironmentsitdidn’treallytake

off,butifyouwantto,youcancreateashellscripttowrapScala:
1#!/bin/sh
2execscala"$0""$@"
3!#
4objectHelloWorld{
5defmain(args:Array[String]){
6println("Hello,"+args.toList)
7}
8}
9HelloWorld.main(args)

Don’tworryaboutthesyntaxorwhatthescriptdoes(althoughI’msureyou’vegota
prettygoodideaalready).TheimportantthingtonoteisthatsomeScalacodehasbeen
embeddedinashellscriptandthatthelastlineisthecommandtorun.
You’dsaveitasa.shfile,forexamplehello.sh,andexecuteitlikethis:
./hello.shWorld!

Theexeccommandonline2spawnsaprocesstocallscalawitharguments;thefirstis
thescriptfilenameitself(hello.sh)andthesecondistheargumentstopasstothescript.
ThewholethingisequivalenttorunningScalalikethis,passinginashellscriptasan
argument:
scalahello.shWorld!

scalac

Ifyou’dprefer,youcancompile.scalafilesusingtheScalacompiler.


Thescalaccompilerworksjustlikejavac.ItproducesJavabytecodethatcanbe
executeddirectlyontheJVM.Yourunthegeneratedbytecodewiththescalacommand.

JustlikeJavathough,it’sunlikelyyou’llwanttobuildyourapplicationsfromthe
commandline.
AllthemajorIDEssupportScalaprojects,soyou’remorelikelytocontinueusingyour
favoriteIDE.We’renotgoingtogointothedetailsofhowtosetupaScalaprojectineach
ofthemajorIDEs;ifyou’refamiliarwithcreatingJavaprojectsinyourIDE,theprocess
willbeverysimilar.
Forreferencethough,hereareafewstartingpoints.
YoucancreatebootstrapprojectswithMavenandthemaven-scala-plugin.
YoucancreateanewScalaprojectdirectlywithinIntelliJIDEAonceyou’ve
installedthescalaplugin(availableintheJetBrainsrepository).
Similarly,youcancreateanewScalaprojectdirectlywithinEclipseonceyouhave
theScalaIDEplugin.Typesafecreatedthisandit’savailablefromtheusualupdate
sites.Youcanalsodownloadabundledirectlyfromthescala-langorscala-ide.org
sites.
YoucanuseSBTandcreateabuildfiletocompileandrunyourproject.SBTstands
forSimpleBuildToolandit’sakintoAntorMaven,butfortheScalaworld.
SBTalsohaspluginsforEclipseandIDEA,soyoucanuseitdirectlyfromwithinthe
IDEtocreateandmanagetheIDEprojectfiles.
1. Ifyoudon’twanttochangeintotheinstallfoldertoruntheREPL,setthebinfolder
onyourpath.↩


SomeBasicSyntax
DefiningValuesandVariables
Let’slookatsomesyntax.We’llstartbycreatingavariable:
vallanguage:String="Scala";

We’vedefinedavariableasaStringandassignedtoitthevalueof“Scala”.Isay
“variable”,butwe’veactuallycreatedanimmutablevalueratherthanavariable.Theval
keywordcreatesaconstant,andlanguagecannotbemodifiedfromthispointon.

Immutabilityisakeythemeyou’llseeagainandagaininScala.
Ifwewillwanttomodifylanguagelater,wecanusevarinsteadofval.Wecanthen
reassignitifweneedto.
varlanguage:String="Java";
language="Scala";

Sofar,thisdoesn’tlookverydifferentfromJava.Inthevariabledefinition,thetypeand
variablenamearetheoppositewayroundcomparedtoJava,butthat’saboutit.However,
Scalausestypeinferenceheavily,soScalaknowsthatthevaraboveisastring,evenifwe
don’ttellit.
vallanguage="Scala";

Similarly,itknowsthattheexpressionisfinishedwithoutneedingtotellitexplicitlywith
thesemicolon.Sowecandropthattoo.
vallanguage="Scala"//nosemicolon

Youonlyneedtoaddsemicolonswhenyouusemultipleexpressionsonthesameline;
otherwisethingsgettoocomplexforthecompiler.
Operatorprecedenceisjustasyou’dexpectinJava.Intheexamplebelow,the
multiplicationhappensbeforethesubtraction.
scala>valage=35
scala>varmaxHeartRate=210-age*.5
res0:Double=191.5

DefiningFunctions
Functionandmethoddefinitionsstartwiththedefkeyword,followedbythesignature.
ThesignaturelookssimilartoaJavamethodsignaturebutwiththeparametertypesthe
otherwayroundagain,andthereturntypeattheendratherthanthestart.
Let’screateafunctiontoreturntheminimumoftwonumbers.
defmin(x:Int,y:Int):Int={

if(xreturnx
else


returny
}

WecantestitintheREPLbycallingit:
scala>min(34,3)
res3:Int=3
scala>min(10,50)
res4:Int=10

NotethatScalacan’tinferthetypesoffunctionarguments.
Anothertrickisthatyoucandropthereturnstatement.Thelaststatementinafunction
willimplicitlybethereturnvalue.
defmin(x:Int,y:Int):Int={
if(xx
else
y
}

RunningittheREPLwouldshowthefollowing:
scala>min(300,43)
res5:Int=43

Inthisexample,theelsemeansthelaststatementisconsistentwithaminfunction.IfI
forgottheelse,thelaststatementwouldbethesameregardlessandtherewouldbeabug

inourimplementation:
defmin(x:Int,y:Int):Int={
if(xx
y//bug!where'stheelse?
}


Italwaysreturnsy:
scala>min(10,230)
res6:Int=230

Ifyoudon’tuseanyreturnstatements,thereturntypecanusuallybeinferred.
//thereturntypecanbeomitted
defmin(x:Int,y:Int)={
if(xx
else
y
}

Notethatit’stheequalssignthatsaysthisfunctionreturnssomething.IfIwritethis
functionononeline,withoutthereturntypeandjusttheequalssign,itstartstolooklikea
realexpressionratherthanafunction.
defmin(x:Int,y:Int)=if(x
Bewary,though;ifyouaccidentallydroptheequalssign,thefunctionwon’treturn
anything.It’llbesimilartothevoidinJava.
defmin(x:Int,y:Int){
if(x

}
<console>:8:warning:apureexpressiondoesnothinginstatementposition;
youmaybeomittingnecessaryparentheses
if(x^
<console>:8:warning:apureexpressiondoesnothinginstatementposition;
youmaybeomittingnecessaryparentheses
if(x^
min:(x:Int,y:Int)Unit

Althoughthiscompilesokay,thecompilerwarnsthatyoumayhavemissedofftheequals
sign.

OperatorOverloadingandInfixNotation
OneinterestingthingtonoteinScalaisthatyoucanoverrideoperators.Arithmetic
operatorsare,infact,justmethodsinScala.Assuch,youcancreateyourown.Earlier,we
sawtheintegerageusedwithamultiplier.
valage:Int
age*.5

Thevalueageisanintegerandthereisamethodcalled*ontheintegerclass.Ithasthe
followingsignature:
def*(x:Double):Double

NumbersareobjectsinScala,asareliterals.Soyoucancall*directlyonavariableora
number.
age.*(.5)
5.*(10)



Usingtheinfixnotation,you’reabletodropthedotnotationforvariablesandliteralsand
call:
age*.5

or,asanotherexample:
35toString

Remember,35isaninstanceofInt.
Specifically,Scalasupportforinfixnotationmeansthatwhenamethodtakeszeroorone
argumentsyoucandropthedotandparentheses,andifthereismorethanoneargument
youcandropthedot.


Forexample:
35+10
"aBCDEFG"replace("a","A")

It’soptionalthough;youcanusethedotnotationifyouprefer.
Whatthismeansisthatyoucandefineyourownplusorminusmethodonyourown
classesanduseitnaturallywithinfixnotation.Forexample,youmighthaveaPassenger
joinaTrain.
train+passenger

Therearenotmanyrestrictionsonwhatyoucancallyourfunctionsandmethods;youcan
useanysymbolthatmakessensetoyourdomain.

Collections
Scalacomeswithitsownimmutablecollectiontypesaswellasmutableversions.By
defaultimmutabilityispreferred,sowecancreatealistwiththefollowing:

vallist=List("a","b","c")

Andcreateamapwith:
valmap=Map(1->"a",2->"b")

wherethearrowgoesfromthekeytothevalue.Thesewillbeimmutable;youwon’tbe
abletoaddorremoveelements.


YoucanprocesstheminasimilarwaytoJava8’sforEachandlambdasyntax:
list.foreach(value=>println(value))//scala

whichisequivalenttothefollowinginJava:
list.forEach(value->System.out.println(value));//java

LikeJava8’smethodreferencesyntax,youcanauto-connectthelambdaargumenttothe
methodcall.
list.foreach(println)//scala

whichisroughlyequivalenttothisJava:
list.forEach(System.out::println);//java

TherearelotsofotherScala-esquewaystoprocesscollections.We’lllookattheselater,
butthemostcommonwaytoiterateisaforloopwrittenlikethis:
for(value<-list)println(value)

whichreads,“foreveryvalueinlist,printthevalue”.Youcanalsodoitinreverse:
for(value<-list.reverse)println(value)

oryoumightliketobreakitacrossmultiplelines:

for(value<-list){
println(value)
}

JavaInteroperability
ImentionedthatyoucanuseanyJavaclassfromScala.Forexample,let’ssaywewantto
createaJavaListratherthantheusualScalaimmutableList.
vallist=newjava.util.ArrayList[String]

Allwedidwasfullyqualifytheclassname(java.util.ArrayList)andusenewto
instantiateit.Noticethesquarebrackets?Scaladenotesgenericsusing[]ratherthan<>.
Wealsodidn’thavetousetheparenthesesontheconstructor,aswehadnoargumentsto
passin.
Wecanmakemethodcalls—forexample,addinganelement—justasyou’dexpect:
list.add("Hello")

or,usinginfix:
listadd"World!"

PrimitiveTypes
InJavatherearetwointegertypes:theprimitive(non-object)intandtheIntegerclass.
Scalahasnoconceptofprimitives—everythingisanobject—so,forexample,Scala’s
integertypeisanInt.Similarly,you’llbefamiliarwiththeotherbasictypes:
Byte
Short
Int


Long
Char

String
Float
Double
Boolean

AlthoughScalahasitsownrichertypes,typicallytheyjustwraptheJavatypes.When
workingwiththesebasictypes,ninetimesoutoftenyouwon’tneedtoworryifyou’re
usingScalaorJavatypes.Thingsareprettyseamless.Forexample,Scalahasa
BigDecimaltypewitha+methodwhichmeansyoucanaddtwobigdecimalswithmuch
lesscodethaninJava.


ComparethefollowingScalatoJava:
//scala
valtotal=BigDecimal(10000)+BigDecimal(200)
//java
BigDecimaltotal=newBigDecimal(10000).add(newBigDecimal(200));

Scalahasn’treimplementedJava’sBigDecimal;itjustdelegatestoitandsavesyouhaving
totypeallthatboilerplate.


Scala’sClassHierarchy
Scala’sclasshierarchystartswiththeAnyclassinthescalapackage.Itcontainsmethods
like==,!=,equals,##,hashCode,andtoString.
abstractclassAny{
finaldef==(that:Any):Boolean
finaldef!=(that:Any):Boolean
defequals(that:Any):Boolean
def##:Int

defhashCode:Int
deftoString:String
//...
}

EveryclassinScalainheritsfromtheabstractclassAny.Ithastwoimmediatesubclasses,
AnyValandAnyRef.


Fig.1.1.EveryclassextendstheAnyclass.


AnyVal
AnyValisthesuper-typetoallvaluetypes,andAnyRefthesuper-typeofallreference

types.
BasictypessuchasByte,Int,Char,etc.areknownasvaluetypes.InJavavaluetypes
correspondtotheprimitivetypes,butinScalatheyareobjects.Valuetypesareall
predefinedandcanbereferredtobyliterals.Theyareusuallyallocatedonthestackbut
areallocatedontheheapinScala.
AllothertypesinScalaareknownasreferencetypes.Referencetypesareobjectsin
memory(theheap),asopposedtopointertypesinC-likelanguages,whichareaddresses
inmemorythatpointtosomethingusefulandneedtobedereferencedusingspecialsyntax
(forexample,*age=64inC).Referenceobjectsareeffectivelydereferenced
automatically.
ThereareninevaluetypesinScala:

Fig.1.2.Scala’svaluetypes.

Theseclassesarefairlystraightforward;theymostlywrapanunderlyingJavatypeand

provideimplementationsforthe==methodthatareconsistentwithJava’sequalsmethod.


Thismeans,forexample,thatyoucancomparetwonumberobjectsusing==andgeta
sensibleresult,eventhoughtheymaybedistinctinstances.
So,42==42inScalaisequivalenttocreatingtwoIntegerobjectsinJavaand
comparingthemwiththeequalsmethod:newInteger(42).equals(newInteger(42)).
You’renotcomparingobjectreferences,likeinJavawith==,butnaturalequality.
Rememberthat42inScalaisaninstanceofIntwhichinturndelegatestoInteger.
Unit

TheUnitvaluetypeisaspecialtypeusedinScalatorepresentanuninterestingresult.It’s
similartoJava’sVoidobjectorvoidkeywordwhenusedasareturntype.Ithasonlyone
value,whichiswrittenasanemptypairofbrackets:
scala>valexample:Unit=()
example:Unit=()

AJavaclassimplementingCallablewithaVoidobjectasareturnwouldlooklikethis:
//java
publicclassDoNothingimplementsCallable<Void>{
@Override
publicVoidcall()throwsException{
returnnull;
}
}


ItisidenticaltothisScalaclassreturningUnit:
//scala
classDoNothingextendsCallable[Unit]{

defcall:Unit=()
}

RememberthatthelastlineofaScalamethodisthereturnvalue,and()representsthe
oneandonlyvalueofUnit.
AnyRef
AnyRefisanactuallyanaliasforJava’sjava.lang.Objectclass.Thetwoare
interchangeable.ItsuppliesdefaultimplementationsfortoString,equalsandhashcode

forallreferencetypes.
ThereusedtobeasubclassofAnyRefcalledScalaObjectthatallScalareferencetypes
extended.However,itwasonlythereforoptimisationpurposesandhasbeenremovedin
Scala2.11.(Imentionitasalotofdocumentationstillreferstoit.)


Fig.1.3.ScalaAny.TheScalaObjectclassnolongerexists.

TheJavaStringclassandotherJavaclassesusedfromScalaallextendAnyRef.
(Rememberit’sasynonymforjava.lang.Object.)AnyScala-specificclasses,like
Scala’simplementationofalist,scala.List,alsoextendAnyRef.

Fig.1.4.Scala’sreferencetypes.

Forreferencetypeslikethese,==willdelegatetotheequalsmethodlikebefore.ForpreexistingclasseslikeString,equalsisalreadyoverriddentoprovideanaturalnotionof
equality.Foryourownclasses,youcanoverridetheequalsjustasyouwouldinJava,but
stillbeabletouse==incode.
Forexample,youcancomparetwostringsusing==inScalaanditwouldbehavejustasit
wouldinJavaifyouusedtheequalsmethod:
newString("A")==newString("A")//trueinscala,falseinjava
newString("B").equals(newString("B"))//trueinscalaandjava



×