Learning Scala - ksree/ProgrammingScala GitHub Wiki
# Case class dosnt have body.
- It creates immutable constructors. Compiler automatically generates methods like toString, equals and hashCode.
- Compiler also create a companion object(Singleton) of the same name.
- Companion object will have several methods added. One of them is apply method.apply method is a factory for creating the object. Or its the way of defining factory method for a class.
- When function return a Unit , its side-effecting.
Higher order function. Function that takes function as arg.
Options is a type that dosnt hold another type.
**## **Partial Functions ****
Partial functions takes an argument of type any and returns a Unit.
PartialFunction[ Any, Unit]
Partial functions only contains case class, which do pattern matching on the messages passed to the function.
def receive = {
case first_pattern = > first_pattern_expressions
case second_pattern = > second_pattern_expressions
}
## Asynchronous messages
! is an asynchronous message.
sender ! Response( s" ShapesDrawingActor: $ s drawn") ' // This is infix notion , because operator ! is between object and message 'sender.!( Response( s" ShapesDrawingActor: $ s drawn"))
Traits. Partial functions Seq, maps,
######### OPTIONS
Options is a abstract class, with two implementations. Some and None.
/////// Packaging In scala package name dosnt need to match the directory structure import java.io.File_ // Import all the types. * cannot be used as in Java, since in scala * is a method name. You can place imports anywhere in your code. so you can scope their visibility where they are needed.
////Type Inference /* Source https://twitter.github.io/scala_school/type-basics.html */ Types in Scala Scala’s powerful type system allows for very rich expression. Some of its chief features are: parametric polymorphism roughly, generic programming
(local) type inference roughly, why you needn’t say val i: Int = 12: Int
existential quantification roughly, defining something for some unnamed type
views roughly, “castability” of values of one type to another
### Variance
Meaning Scala notation
**covariant **C[T’] is a subclass of C[T] [+T]
**contravariant **C[T] is a subclass of C[T’] [-T]
**invariant **C[T] and C[T’] are not related [T]
So functions are contravariant in their parameter types and covariant in their return types.
################## Scala no argument funtions ########### Omit paranthesis for no argument functions that have no side effects, when method performs side effects then paranthesis are added, this is to caution the users that the mutation may occur. Functions that use other functions as arguments and or return types are called higher order functions. #################### Functions first-class ################## Functions are first class in scala, meaning that they can not just be declared or invoked but can be used in every segment of the language just as any other data type. . A first-class function may, as with other data types, be created in literal form without ever having been assigned an identifier; be stored in a container such as a value, variable, or data structure; and be used as a parameter to another function or used as the return value from another function. eg - map() or reduce() reduce take function parameter, and uses it to reduce a collection of items to a single item The popular Map/Reduce computing paradigm uses this concept to tackle large computing challenges, by mapping the computation across a range of distributed nodes and reducing their results back to a meaningful size.
Functions are objects with apply method.
########################### Partially applied functions ##################### A function with multiple arguments, you can create a new function by omitting one or more of the trailing argument list .This is called partially applied functions. ############################## Partial functions ################## partial functions take a single argument of some type , but is not defined for all the values of that type. http://blog.bruchez.name/2011/10/scala-partial-functions-without-phd.html
Seq, Set or Map is actually a partial function
The PartialFunction trait supports the lift method, which converts the partial function to a normal function Lift returns a function that returns an Option of values.
#################Tail call recursions ################# When the function calls itself and the call is the final(tail) operation it does.
##################Curryging ########### Currying transforms a function taking multiple argument list into series of functions taking single arguments.
##############Sequence is not immutable ####################
scala.collection // Basic collections are neither mutable or immutable. They just provide functionality.
scala.collection.immutable
scala.collection.mutable
#################OOP In scala ######################## Scala promotes is using functional programming in small and oop in large. Using functional programming for implementing algorithms,manipulating data and managing state in a principle way is the best way to minimizing bugs and amount of code we write.
On the other hand scalas OO model provides tool for creating composable, resusable modules which are essential for large applications.
Classes and Object
Classes are declared with key word class.
Objects are singleton and are declared with object.
To avoid derived classes to be created from a class, prefix final.
Use abstract to prevent instantiation of the class, such as when it contains or inherits member declarations without providing concrete definitions for them.
Method usually refers to function that is tied to an instance.
If an object and class have the same name are if they are defined in the same file, then they are called companions. For Case classes, the compiler automatically creates companion for you.
All reference types are subtypes of AnyRef -- These are instantiated using new All value types are subtypes of AnyVal value types are : Short, Int, Long, Float,Double, Boolean, Char, Byte , Unit -- instances are stored on the stack.
Unit behaves like a Zero tupe. Hence ()
###########Constructors in Scala Primary constructor is the entire body of the class
Any parameters that the constructor require are listed after the class name.
#################Case class We can derive a case class from a non case class and vice versa. But we cannot derive a case class from another.This is because the auto generated implementations of toString, equals ,and hasCode,do not work properly for subClasses, meaning that they ingnore the possiblity that the instance could be a derived type of the case class type. Case class provide convinient domain types, with pattern matching and decomposition of instances of these types.Supporting inheritance hierarchies is not their purpose.
##############Inheritance Rules
- Abstract base class or traits is subclassed one level by a concrete class or a case class. 2 Concrete classes are never subclassed, except a. Classes that mix in other behaviours defined in traits. b. Test only version to perform unit testing.
- When subclassing seems the right approach , consider partitioning behaviours into traits and mix in those traits instead.
- Never split logical state accross parent-child type boundaries.
########## Covariant & Contravariatn List is a covariant type.
Scala Java
+T ? extends T Covariant
-T ? super T Contravariant
T T Invariant.cannt substitute Y[Tsup] or y[Tsub] or Y[T]
List[T] is a Covariant
Best example of Contravariant is set of traits FunctionN, such as scala.Function2 where N is between 0 to 22
Scala Function2: trait Function[-T1, -T2, +R] extends AnyRef
Scala Types: Noting is a subclass of all other types. Value types and Reference Types. Null is a subclass of all reference Types.
Equal and == operators: both checks the equality on the value and NOT the reference.
The eq and ne Methods: The eq and ne Methods tests for reference equality. That is obj1 and obj2 are equal if they both point to the same location in memory.
Reduce Left vs Reduce Right: http://stackoverflow.com/questions/1446419/how-do-you-know-when-to-use-fold-left-and-when-to-use-fold-right
List(1,2,3).foldRight(0)(_ + _) Would reduce to the bellow, here .1 is accumulator and .2 is the list value 1 + List(2,3).foldRight(0)(+)
2 + List(3).foldRight(0)(_+_)
3 + 0
List(1,2,3).foldLeft(0)(+) Would reduce to the bellow . (((0 + 1) + 2) + 3)