Note
InScala,thetypeofavariableorfunctioniswrittenafter
thenameofth evariableorfunction.Thismakesite asier
toreaddeclarationswithcomplextypes.
AsImovebackandforthbetweenScalaandJava,Ifind
thatmyfingerswriteJava declarationssuchasString
greetingon autopilot,soIhavetorewritethemas
greeting:String.Thisisabitannoying,butwhenI
workwithcomplexScalaprograms,Ireallyappreciate
thatIdon’thavetodecryptCstyletypedeclarations.
Note
Youmayhavenoticedthattherewerenosemicolons
aftervariabledeclarationsorassignments.InScala,
semicolonsareonlyrequiredifyouhavemultiple
statementsonthesameline.
Youcandeclaremultiplevaluesorvariablestogether:
Clickheretoviewcodeimage
valxmax,ymax=100//Setsxmaxandymaxto100
vargreeting,message:String=null
//greetingandmessagearebothstrings,initializedwithnull
1.3 COMMONLY US ED TYPES
YouhavealreadyseensomeofthedatatypesofScala,suchasIntand
Double.LikeJava,Scalahassevennumerictypes:Byte,Char,Short,Int,
Long,Float,andDouble,andaBooleantype.However,unlikeJava,
thesetypesareclasses.Thereisnodistinctionbetweenprimitivetypesand
classtypesinScala.Youcaninvokemethodsonnumbers,forexample:
Clickheretoviewcodeimage
1.toString()//Yieldsthestring"1"
or,moreexcitingly,
Clickheretoviewcodeimage
1.to(10)//YieldsRange(1,2,3,4,5,6,7,8,9,10)
(WewilldiscusstheRangeclassinChapter13.Fornow,justviewitasa
collectionofnumbers.)
InScala,thereisnoneedforwrappertypes.ItisthejoboftheScala
compilertoconvertbetweenprimitivetypesandwrappers.Forexample,if
youmakeanarrayofInt,yougetanint[]arrayinthevirtualmachine.
AsyousawinSection1.1,“TheScalaInterpreter,”onpage1,Scalarelieson
theunderlyingjava.lang.Stringclassforstrings.However,itaugments
thatclasswithwelloverahundredoperationsintheStringOpsclass.For
example,theintersectmethodyieldsthecharactersthatarecommonto
twostrings:
Clickheretoviewcodeimage
"Hello".intersect("World")//Yields"lo"
Inthisexpression,thejava.lang.Stringobject"Hello"isimplicitly
convertedtoaStringOpsobject,andthentheintersectmethodofthe
StringOpsclassisapplied.So,remembertolookintotheStringOpsclass
whenyouusetheScaladocumentation(seeSection1.7,“Scaladoc,”onpage
10).
Similarly,thereareclassesRichInt,RichDouble,RichChar,andsoon.
Eachofthemhasasmallsetofconveniencemethodsforactingontheirpoor
cousins—Int,Double,orChar.Thetomethodthatyousawaboveis
actuallyamethodoftheRichIntclass.Intheexpression