Scala for Java Developers A Practical Primer 1st Edition Toby Weston pdf download
Scala for Java Developers A Practical Primer 1st Edition Toby Weston pdf download
https://textbookfull.com/product/scala-for-java-developers-a-
practical-primer-1st-edition-toby-weston/
https://textbookfull.com/product/mastering-corda-blockchain-for-
java-developers-1st-edition-jamiel-sheikh/
https://textbookfull.com/product/quantum-computing-for-
developers-a-java-based-introduction-meap-v09-johan-vos/
https://textbookfull.com/product/java-cookbook-problems-and-
solutions-for-java-developers-early-release-ian-f-darwin/
https://textbookfull.com/product/introducing-maven-a-build-tool-
for-today-s-java-developers-second-edition-balaji-varanasi/
Java Cookbook Problems and Solutions for Java
Developers final release 4th Edition Ian F. Darwin
https://textbookfull.com/product/java-cookbook-problems-and-
solutions-for-java-developers-final-release-4th-edition-ian-f-
darwin/
https://textbookfull.com/product/schizophrenia-a-practical-
primer-2nd-edition-keshavan/
https://textbookfull.com/product/practical-social-engineering-a-
primer-for-the-ethical-hacker-1st-edition-joe-gray/
https://textbookfull.com/product/practical-bayesian-inference-a-
primer-for-physical-scientists-1st-edition-coryn-a-l-bailer-
jones/
https://textbookfull.com/product/a-rulebook-for-arguments-5th-
edition-anthony-weston/
Toby Weston
If you don’t see the scala> prefix, assume the fragment may
depend on previous code examples. I’ve tried to introduce these
logically, balancing the need to show complete listings with trying to
avoid pages and pages of dry code listings.
If things don’t make sense, always refer to the full source code.
In short, you may find it useful to consult the full source while you
read.
scala> : paste
// Entering paste mode (ctrl-D to finish)
val x = 4
val y = 34
x + y * 2
// press Ctrl + D
res1: Int = 72
Source Code
The source code for this book is available at GitHub:
https://github.com/tobyweston/learn-scala-java-
devs . You can clone the repository or download an archive directly
from the site.
The source code is licensed under Apache 2.0 open source
license.
The Past
The Future
Getting Started
Scala Scripts
scalac
Defining Functions
Collections
Tuples
Java Interoperability
Primitive Types
Chapter 4:Scala’s Class Hierarchy
AnyVal
Unit
AnyRef
Bottom Types
Chapter 5:ScalaDoc
Functional Programming
Chapter 7:Summary
Creating Classes
Summary
Additional Constructors
Using Default Values
Singleton Objects
Companion Objects
Anonymous Functions
Anonymous Classes
First-class Functions
Passing in Functions
Returning Functions
Storing Functions
Function Types
Functions vs.Methods
Lambdas vs.Closures
Chapter 11:Inheritance
Subtype Inheritance
Anonymous Classes
Interfaces/Traits
Methods on Traits
Abstract Classes
Polymorphism
Conditionals
Switch Statements
Exceptions
Chapter 13:Generics
Parametric Polymorphism
Class Generics
Method Generics
Stack Example
Bounded Classes
Multiple Bounds
Variance
Invariance
Covariance
Contravariance
Variance Summary
Summary
Higher-Order Functions
Call-by-Name
Currying
Summary
Switching
Patterns
Literal Matches
Constructor Matches
Type Query
Guard Conditions
Mapping Functions
FlatMap
Chapter 18:Monads
Basic Definition
Option
The map Function
Option.get
Option.getOrElse
Summary
Summary
Goals
Chapter 22:Tips
Be Clear
Get Guidance
Have a Plan
Conventions
What to Avoid
Other Challenges
Inheritance
Generics
Pattern Matching
Constructor Matches
Map
Mapping Functions
FlatMap
Index
About the Author and About the
Technical Reviewer
About the Author
Toby Weston
is an independent software developer based in London. He
specializes in Java and Scala development, working in agile
environments. He’s a keen blogger and writer, having written for
JAXenter and authored the books Essential Acceptance Testing
(Leanpub) and Learning Java Lambdas (Pact).
The Past
Scala started life in 2001 as a research project at EPFL in
Switzerland. It was released publicly in 20041 after an internal
release in 2003. The project was headed by Martin Odersky, who’d
previously worked on Java generics and the Java compiler for Sun
Microsystems.
It’s quite rare for an academic language to cross over into
industry, but Odersky and others launched Typesafe Inc. (later
renamed Lightbend Inc.), a commercial enterprise built around
Scala. Since then, Scala has moved firmly into the mainstream as a
development language.
Scala offers a more concise syntax than Java but runs on the
JVM. Running on the JVM should (in theory) mean an easy migration
to production environments; if you already have the Oracle JVM
installed in your production environment, it makes no difference if
the bytecode was generated from the Java or Scala compiler.
It also means that Scala has Java interoperability built in, which
in turn means that Scala can use any Java library. One of Java’s
strengths over its competitors was always the huge number of open
source libraries and tools available. These are pretty much all
available to Scala too. The Scala community has that same open
source mentality, and so there’s a growing number of excellent
Scala libraries out there.
The Future
Scala has definitely moved into the mainstream as a popular
language. It has been adopted by lots of big companies including
Twitter, eBay, Yahoo, HSBC, UBS, and Morgan Stanley, and it’s
unlikely to fall out of favour anytime soon. If you’re nervous about
using it in production, don’t be; it’s backed by an international
organization and regularly scores well in popularity indexes.
The tooling is still behind Java though. Powerful IDEs like
IntelliJ’s IDEA and Eclipse make refactoring Java code
straightforward but aren’t quite there yet for Scala. The same is
true of compile times: Scala is a lot slower to compile than Java.
These things will improve over time and, on balance, they’re not the
biggest hindrances I encounter when developing.
Scala’s future is tied to the future of the JVM and the JVM is still
going strong. Various other functional languages are emerging
however; Kotlin and Clojure in particular are interesting and may
compete. If you’re not interested in JVM based languages but just
the benefits of functional programming, Haskel and ELM are
becoming more widely adopted in industry.
Footnotes
1 See Odersky, “A Brief History of Scala” on Artima and wikipedia for more background.
© Toby Weston 2018
Toby Weston, Scala for Java Developers, https://doi.org/10.1007/978-1-4842-
3108-1_2
2. Installing Scala
Toby Weston1
(1) London, UK
Getting Started
There are a couple of ways to get started with Scala .
1. Run Scala interactively with the interpreter.
scala> _
scala> 42*4
res0: Int = 168
:quit
Scala Scripts
The creators of Scala originally tried to promote the use of Scala
from Unix shell scripts . As competition to Perl, Groovy, or bash
scripts on Unix environments it didn’t really take off, but if you want
to you can create a shell script to wrap Scala.
1 #!/bin/sh
2 exec scala "$0" "$@"
3 !#
4 object HelloWorld {
5 def main(args: Array[String]) {
6 println("Hello, " + args.toList)
7 }
8 }
9 HelloWorld.main(args)
Don’t worry about the syntax or what the script does (although
I’m sure you’ve got a pretty good idea already). The important thing
to note is that some Scala code has been embedded in a shell script
and that the last line is the command to run.
You’d save it as a .sh file—for example, hello.sh—and
execute it like this:
./hello.sh World!
No. 2.
Play music.
No. 3.
Play music.
As conches, the two large shells, Triton and Cassis are commonly
used. For this purpose, a hole is pierced for the lips on the side of
the spire.
Dancing is performed on very different occasions in these islands.
Besides the war, funeral, and festal dances, there are others which
partake of a lascivious character both in the words of the
accompanying chant and in the movements of the hands and body.
Whilst visiting the small island of Santa Catalina, I saw one of these
dances performed by young girls from 10 to 14 years of age. An
explanation of their reluctance to commence, which at first from my
ignorance of what was to follow I was at a loss to understand, soon
offered itself in the character of the dance, and evidently arose from
a natural sense of modesty that appeared strange when associated
with their subsequent performance. There are, however, other
dances, purely sportive in their nature. Of such a kind were some
which were performed for my benefit at the village of Gaeta in the
Florida Islands. About twenty lads, having formed a ring around a
group of their companions squatting in the centre, began to walk
slowly round, tapping the ground with their left feet at every other
step, and keeping time with a dismal drone chanted by the central
group of boys. Every now and then the boys of the ring bent forward
on one knee towards those in the middle, while at the same time
they clapped their hands and made a peculiar noise between a hiss
and a sneeze: the chant then became more enlivening and the
dancing more spirited. On the following day the women of the
village took part in a dance which was very similar to that of the
boys, except that there was no central group, and that they wore
bunches of large beans around the left ankle which made a rattling
noise when they tapped the ground at every other step with the left
foot. Bishop Selwyn, to whom I was indebted for the opportunity of
witnessing these dances in the village of Gaeta, informed me that in
the Florida Islands, dancing is often more or less of a profession,
troupes of dancers making lengthened tours through the different
islands of this sub-group.
During a great feast that was held in the island of Treasury, the
following dance was performed. Between thirty and forty women
and girls stood in a ring around a semi-circular pit, 5 feet across,
which was sunk about 4 feet in the ground. A board, which was
fixed in the pit about half way down, covered it in with the exception
of a notch at its border. On this board stood two women, and as
they danced they stamped with their feet, producing a dull hollow
sound, to which the women of the circle timed their dancing, which
consisted in bending their bodies slightly forward, gently swaying
from side to side, and raising their feet alternately. All the while, the
dancers sang in a spirited style different native airs. Now and then, a
pair of women would dance slowly round outside the circle, holding
before them their folded pandanus mats which all the performers
carried.[129]
[129] The employment of a hole in the ground as a resonator does not
appear to be common. Mr. Mosely in his “Notes by a Naturalist,” p. 309,
refers to a somewhat similar use of holes in the ground by the Fijians who
place a log-drum of light wood over three holes and strike it with a
wooden mallet.
I was present at a dance given on one occasion at Alu, preparatory
to a great feast which was about to be held. Soon after sunset the
natives began to assemble on the beach, and when Gorai, the chief,
arrived on the scene, between thirty and forty men arranged
themselves in a circle, each carrying his pan-pipe. They began by
playing an air in slow time, accompanying the music by a slight
swaying motion of the body, and by alternately raising each foot.
Then the notes became more lively and the movements of the
dancers more brisk. The larger pipes took the part of the bass in a
rude but harmonious symphony, whilst the monotonous air was
repeated without much variation in the higher key of the smaller
instruments. At times one of the younger men stopped in the centre
of the ring, tomahawk in hand, and whilst he assumed a half-
stooping posture, with his face looking upwards, the musicians dwelt
on the same note which became gradually quicker and louder, whilst
the dancing became more brisk, until, when the tip-toe of
expectation was apparently reached, and one was beginning to feel
that something ought to happen, the man in the centre who had
been hitherto motionless, swung back a leg, stuck his tomahawk in
the ground, and one’s feelings were relieved by the dull monotone
suddenly breaking off into a lively native air. . . On another occasion,
I was present at a funeral or mourning dance, which was held in
connection with the death of the principal wife of the Alu chief. It will
be found described on page 48.
I will conclude this chapter by alluding to a favourite game of the
Treasury boys which reminded me somewhat of our English game of
peg-tops. An oval pebble about two inches long is placed on a leaf
on the ground. Each boy then takes a similar pebble, around which a
piece of twine is wound; and standing about eight feet away, he
endeavours in the following manner to throw it so as to fall on the
pebble on the ground. The end of the twine is held between his
fingers; and as the twine uncoils, he jerks it backwards and brings
his pebble with considerable force on top of the other.
CHAPTER VIII.
CANOES—FISHING—HUNTING.
I should here remark that, when fishing on the reefs, natives are
sometimes struck by the gar-fish with such force that they die from
the wound. The possibility of this occurrence has recently been
doubted. But that such is the case, we incidentally learned from the
natives of the Shortlands. The people of Wano, on the north coast of
St. Christoval, believe that the ghosts which haunt the sea, cause
the flying-fish and the gar-fish to dart out of the water and to strike
men in the canoes; and they hold that any man thus struck will die.
[139] This superstitious belief could only have arisen from the
circumstance of natives having met their death in this manner; and
it is probable that in this respect the larger flying-fish would be quite
as much to be feared as the gar-fish. Mr. Moseley, in his “Notes by a
Naturalist,” p. 480, refers to such an event as not of uncommon
occurrence in some of the Pacific Islands.[140]
[139] “Religious Beliefs and Practices in Melanesia,” by the Rev. R. H.
Codrington, M.A. Journal of Anthropological Institute, vol. X.
[140] Vide also “Nature,” index of vol. XXVIII., for some further
correspondence on this subject.
[144] Dillon’s “Discovery of the Fate of La Pérouse” (1829), vol I., p. lxix.
Wild dogs are numerous in the bush in the interior of Alu. They
never attack the natives or the pigs and, as they always slink away
when alarmed, they are not often seen. They subsist on the
opossums (Cuscus), waiting to catch them at the foot of the trunks
of the trees as they descend to the ground at nightfall. When I was
away on an excursion with Gorai the Alu chief, the native dogs that
were with us ran down a wild dog and worried it to death. I came in
at the death, and was not very much pleased with the spectacle
which afforded much amusement to Gorai and his men. The
unfortunate dog was apparently of the native breed. How these
animals have come to prefer this mode of life I could not learn.
My native companions during my excursions rarely returned to their
homes without bringing back an opossum (Cuscus). Usually this
animal was caught without much trouble, as it slumbers during the
day and may be then surprised amongst the foliage of the tree
where it finds its home. Sometimes, however, when the keen eyes of
my natives discovered an opossum amongst the leafy branches
overhead, we were enlivened by an exciting hunt. On such
occasions, one man climbs the tree in which the animal is esconced
whilst three or four other men climb the trees immediately around.
By dint of shouting and shaking the branches, the opossum is
started from its retreat, and then the sport commences. This clumsy
looking creature displays great agility in springing from branch to
branch, and even from tree to tree. Suspended by its prehensile tail
to the branch above, the Cuscus first tests the firmness of the
branch next below, before it finally intrusts its weight to its support.
It runs up and down the stouter limbs of the tree like a squirrel; but
its activity and cunning are most displayed in passing from the
branches of one tree to those of another. At length, scared by the
shaking of the branches, and by the cries of the natives who have
clambered out on the limbs as far as they can get with safety, the
opossum runs out towards the extremity of the limb, proceeding
cautiously to the very terminal branchlets, until the weight of its
body bends down the slender extremities of the branch, and it hangs
suspended by its tail in mid-air about ten feet below. The gentle
swaying of the branches in the wind, aided probably by its own
movements, swings the opossum to and fro, until it approaches
within grasp of the foliage of the adjoining tree. Then the clever
creature, having first ascertained the strength of its new support,
uncoils its tail. Up goes the branch with a swish when relieved of its
weight; and in a similar manner the opossum swings by its tail from
the slender branches of the tree to which it has now transferred its
weight. Finally the opossum reaches the ground, where its awkward
movements render it an easy capture. It is then tied to a stick and
carried home alive on the shoulder of a native.
The Cuscus is a common article of food with these islanders; and in
some islands, as in Simbo or Eddystone, it is kept as a pet by the
natives. Out of seven opossums that were kept as pets on board the
“Lark,” all died within a few weeks, being apparently unable to
withstand captivity. Most of them, however, were young. The cause
of the death of one of them was rather singular. Immediately after
its death the skin of the animal was literally covered with small ticks
about the size of a pin’s head and distended with blood, whilst the
body presented the blanched appearance of an animal bled to death.
It had been ailing for a day or two before and was incessantly
drinking all liquids it could get, even its own urine: but the ticks had
not been sufficiently numerous to be observed; and in fact they
appeared to have covered the animal in the course of a single night.
As I was informed by the natives of Simbo, these animals subsist on
the shoots and young leaves of the trees: on board the “Lark” they
cared for little else than bananas. They make a curious clicking noise
when eating, and often hold the substance in their fore-paws. When
taken out in the day-time from their boxes they were half asleep,
and at once tried to get out of the bright light into the shade. In the
night-time they were very restless in their prisons, making continual
efforts to escape between the bars, and as soon as they were let out
they moved about with much activity. The older animals are
sometimes rather fierce. One of them which belonged to the men
used to spend a considerable portion of its time up aloft; and, when
in want of food, it would descend the rigging and go down to the
lower deck. Their naked tails have a cold clammy feeling; and with
them they were in the habit of swinging themselves from any object.
When the Cuscus was about to be taken up by its master, it moored
itself to the nearest object by means of its tail. It always descended
a rope head first, but kept its tail twined round the rope during its
descent so as to be able to withdraw itself at once if necessary, the
tail supporting the greater portion of its weight.
Although the natives, who accompanied me in my various
excursions, usually displayed their skill in following a straight course
through a pathless wood where they could only see a few yards on
either side of them, yet on more than one occasion they were, to
use a nautical phrase, completely out in their reckoning, and I had
to bring my compass into use and become the guide myself in order
to avoid passing the night in the bush. When in the interior of the
north-west part of Alu accompanied by Gorai, the chief, and a
number of his men, I was astonished at the readiness with which, in
the absence of any tracks, they found their way to the coast. Gorai
led the way; and on my asking him how he managed to know the
right direction in a thick forest with neither sun nor trade-wind to
guide him, he merely remarked that he “saveyed bush,” and pointing
with his hand in a particular direction, he informed me that “Mono
stopped there,” Mono being the native name for Treasury. There was
a little uncertainty among the natives as to whether the old chief
was guiding us aright; but there was no hesitation on the part of
Gorai, whose course as tested by my compass was always in the
same direction; he, however, disdained the use of the compass and
ultimately brought us back to the coast. When passing through a
district with which he is but little acquainted, the native frequently
bends the branches of the bushes as he passes, in order to strike
the same path on the way back. He must be frequently guided in his
course through the forest by noticing the bearing of the sun and the
swaying of the upper branches of the trees in the trade-wind, guides
which were often employed by myself when alone in the bush: but
when, as not uncommonly happens, there is such a dense screen of
foliage overhead, that neither the sun nor the upper branches of the
trees can be seen, he must employ other means of guidance. Rude
tracks, usually traversed the least frequented districts of the islands
which we visited; and their persistence appeared to be sometimes
due to the fact that they were used by the wild pigs.
Fallen trees commonly obstruct the most frequented paths in the
vicinity of villages: and there they remain until decay removes them,
for the native has no idea of doing an act for the public weal: with
him, in such and kindred matters, what is everybody’s business is
nobody’s. Captain Macdonald, in his capacity as a chief in Santa
Anna, adopted the serviceable method of employing natives, who
had committed petty offences, in making good walks in the vicinity
of the houses of the white residents. The example however was not
followed by the natives for the approaches to their own village of
Sapuna. Being quite content with their narrow footpaths, they
probably could not understand that whatever contributed to the
public good was also to the advantage of the individual.
CHAPTER IX.
PREVALENT DISEASES.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com