PragPub 2011-10: Issue #28 by The Pragmatic Bookshelf
Author:The Pragmatic Bookshelf
Language: eng
Format: epub, mobi
Tags: PragPub—Monthly Magazine
Publisher: The Pragmatic Bookshelf, LLC
Published: 2011-10-01T04:00:00+00:00
Scala for the Intrigued
Sensible Typing and Optional Items
by Venkat Subramaniam
In this second installment of this series on the Scala programming language, Venkat shows how Scala’s static typing leads to low ceremony programming.
In this second part of the series we will look at the statically typed nature of Scala and its low ceremony.
Java programmers are used to static typing. Scala is also statically typed. However, it employs type inference to figure out types at compile time. So for the most part, you don’t have to specify type information. While Scala provides type inference, it does not go to extremes to determine the type (like F#, for example, which will analyze the method body to figure out types of parameters). Scala type inference reduces the number of keystrokes you have to type and reduces noise in code without compromising readability or understandability.
Let’s first look at how we’d define a variable, set its type, and assign it an initial value. Then we can look at what type inference buys us.
var greet : String = "hello"
You use var to define a mutable variable, a variable whose value can change (true to its varying nature). When defining a variable, use a colon to separate the name of the variable from its type. Finally you can assign a value to the variable using the all-too-familiar equals operator.
Let’s extend that example to change the variable’s value and print the new value.
var greet : String = "hello"
println(greet)
greet = "howdy"
println(greet)
We initialized the variable greet to “hello” and then changed it to “howdy.” The output from the code is shown below:
hello
howdy
At this point if you listen keenly you may hear Scala laughing at the redundancy in typing. Scala already knows that greet is of type String from the fact that its value was initialized to “hello.” So, the : String part is redundant, and you can omit it:
var greet = "hello"
println(greet)
greet = "howdy"
println(greet)
Scala infers the type of the variables at compile time. If Scala notices any ambiguity or errors, it will report right away and will not run any part of the code.
Let’s see what happens if we try to set a value of the greet variable to something not compatible with its type:
var greet = "hello"
println(greet)
greet = 1
println(greet)
When you try to run this script, you will get an error:
error: type mismatch;
found : Int(1)
required: java.lang.String
greet = 1
Scala is quick to tell us that the value 1 we’re assigning to the variable does not match with the type String, the type which it inferred at the point of declaration.
Scala’s type inference plays well far beyond simple variable declarations, too. For instance, in the declaration
val numbers : List[Int] = List(1, 2, 3)
the type declaration is redundant and you can write it as:
val numbers = List(1, 2, 3)
I must acknowledge that this can be a blessing or a curse, depending on how you look at it. numbers is inferred as a List[Int] based on the values you present to the list. If all the values are of the same type, then this is not a concern.
Download
PragPub 2011-10: Issue #28 by The Pragmatic Bookshelf.mobi
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
Personalized inhaled bacteriophage therapy for treatment of multidrug-resistant Pseudomonas aeruginosa in cystic fibrosis by unknow(174746)
CONSORT 2025 statement: updated guideline for reporting randomized trials by unknow(83131)
Critical evaluation of the ProfiLER-02 study design and outcomes by Vivek Subbiah & Razelle Kurzrock(82813)
Cardiac gene therapy makes a comeback by Oliver J. Müller & Susanne Hille & Anca Kliesow Remes(82633)
Whisky: Malt Whiskies of Scotland (Collins Little Books) by dominic roskrow(74436)
Unveiling the design rules for tunable emission in graphene quantum dots: A high-throughput TDDFT and machine learning perspective by Şener Özönder & Mustafa Coşkun Özdemir & Caner Ünlü(50890)
A yeast-based oral therapeutic delivers immune checkpoint inhibitors to reduce intestinal tumor burden by unknow(40259)
Covalent hitchhikers guide proteins to the nucleus by Alexander F. Russell & Madeline F. Currie & Champak Chatterjee(40215)
Meet the Authors: Christopher R. Mansfield and Emily R. Derbyshire by Christopher R. Mansfield & Emily R. Derbyshire(40093)
Alkaline-earth metals promote propane dehydrogenation with carbon dioxide through geometric effects: Altering the reaction pathway by unknow(32729)
Induced iron vacancies boosting FeOOH loaded on sustainable Fenton-like collagen fiber membrane for efficient removal of emerging contaminants by unknow(32504)
Efficient electric-field-assisted photochemical conversion of methane to n-propanol exclusively over penetrated TiO2Ti hollow fibers by Guanghui Feng(32452)
Bi2SiO5 nanosheets as piezo-photocatalyst for efficient degradation of 2,4-Dichlorophenol by Hangyu Shi & Yifu Li & Lishan Zhang & Guoguan Liu & Qian Zhang & Xuan Ru & Shan Zhong(32383)
A novel NDIPTA organic heterojunction photocatalyst with built-in electric field for efficient hydrogen production by Jiahui Yang & Baojun Ma & Yongfa Zhu(32360)
Enhanced conversion of methane to liquid-phase oxygenates via hollow ferrite nanotube@horseradish peroxidase based photoenzymatic catalysis by Jun Duan & Shiying Fan & Xinyong Li & Shaomin Liu(32330)
Ordered macroporous superstructure of defective carbon adorned with tiny cobalt sulfide for selective electrocatalytic hydrogenation of cinnamaldehyde by Xiao-Shi Yuan & Sheng-Hua Zhou & San-Mei Wang & Wenbo Wei & Xiaofang Li & Xin-Tao Wu & Qi-Long Zhu(32256)
What's Done in Darkness by Kayla Perrin(27144)
Topological analysis of non-conjugated ethylene oxide cored dendrimers decorated with tetraphenylethylene: Insights from degree-based descriptors using the polynomial approach by A Theertha Nair & D Antony Xavier & Annmaria Baby & S Akhila(26522)
Investigation of mechanical and self-healing properties of hydroxyl-terminated polybutadiene functionalized with 2-ureido-4-pyrimidinone by Mohsen Kazazi & Mehran Hayaty & Ali Mousaviazar(26457)