Scala--commonly used 1
Recently I transit to use scala to program.
scala is a functional and objected oriented language, but it has seamless java Interoperability (they both run in JVM and freely mixed).
Compared to the java that I am familiar to, there are some common concepts, data structure functions I often use in Scala,
They are also some kinds of distinctions from Java object oriented language. I put here also for quick search afterwards.
(1) var: define variable;
val: deine a constant
e.g.
var i = 0; i = i + 1 // i can be changed
val i: Int = 0 //i value is not allowed to change
(2) object
Everything is object;
e.g. even basic data structure Int are interpreted as
abstract final
class
Int(3) difference between object and class:
Simple differences:
Object: A singleton is a class that can have only one instance, it is like the static field and method in the java class , but it can extend another superclass, implement interfaces,
Class is that you can have multiple instances of a class.
e.g.
object A extends B with C { def f(x: Any): Any = ??? }
It declares an anonymous (inaccessible) class that extends bothB
andC
, and creates a single instance of this class namedA
.
(4) Option/Some/None pattern
Scala uses option to avoid the null or null pointer problem in Java etc.
it use values that may be present or not: the
Option[A]
trait.Some
extends Option
, so it inherits everything except get
and isEmpty
(and some other methods implemented by a case class).None also extend option
In a word,
Option
/ \
/ \
/ \
Some None
Option is container base which can be empty or full
While Some(x) represent full with 'x' being present in the container, None represents empty.
val a: Option[String] = Option(null) // a will be None
val b: Option[String] = Option("Hello!") // "hello"
(4) trait
Similar to java's interface, it encapsulates method and field definitions. It can also be used to define object types by specifying the signature of the supported methods.
example:
trait Equal { def isEqual(x: Any): Boolean def isNotEqual(x: Any): Boolean = !isEqual(x) } class Point(xc: Int, yc: Int) extends Equal { var x: Int = xc var y: Int = yc def isEqual(obj: Any) = obj.isInstanceOf[Point] && obj.asInstanceOf[Point].x == y }
(5) case class
It defines abstract or concrete properties in an abstract base class (or trait) that can be referenced in all child classes.
Case classes are compared by structure and not by reference:
case class Message(sender: String, recipient: String, body: String)
val message1 = Message("jorge@catalonia.es", "guillaume@quebec.ca", "Com va?")
You can create a deep copy of an instance of a case class simply by using the
copy
method. You can optionally change the constructor arguments.val message2 = message1.copy(sender = message4.recipient, recipient = "claire@bourgogne.fr")
It can be used to construct the struct data structure in c/c++
reference: