Wednesday, November 2, 2016

Programming in Scala 11/12/13/14/15

1.
Any is a superclass of every other class, Nothing is a subclass of every other class.
== and !=, are declared final in class Any, so they cannot be overridden in subclasses.
2.
Class Null is the type of the null reference; it is a subclass of every reference class (i.e., every class that
itself inherits from AnyRef). Null is not compatible with value types. You cannot, for example, assign

a null value to an integer variable.
Type Nothing is at the very bottom of Scala's class hierarchy; it is a subtype of every other type.
you can
do anything in a trait definition that you can do in a class definition, and the syntax looks exactly the
same, with only two exceptions.
First, a trait cannot have any "class" parameters.
The other difference between classes and traits is that whereas in classes, super calls are statically
bound, in traits, they are dynamically bound. If you write "super.toString" in a class, you know exactly
which method implementation will be invoked. When you write the same thing in a trait, however, the
method implementation to invoke for the super call is undefined when you define the trait.
3.
Using the modifier case makes the
Scala compiler add some syntactic conveniences to your class.
First, it adds a factory method with the name of the class.
The second syntactic convenience is that all arguments in the parameter list of a case class implicitly
get a val prefix, so they are maintained as fields.
Finally, the compiler adds a copy method to your class for making modified copies.
However, the biggest advantage
of case classes is that they support pattern matching.
4.
Constant patterns:
def describe(x: Any) = x match {
case 5 => "five"
case true => "truth"
case "hello" => "hi!"
case Nil => "the empty list"
case _ => "something else"
}
Scala uses a simple lexical rule for disambiguation: a simple
name starting with a lowercase letter is taken to be a pattern variable; all other references are taken to
be constants.

If that
does not work (because pi is a local variable, say), you can alternatively enclose the variable name in
back ticks. For instance, `pi` would again be interpreted as a constant, not as a variable




No comments:

Post a Comment