Skip to content

Instantly share code, notes, and snippets.

@jamesrajendran
Created May 7, 2017 04:45
Show Gist options
  • Save jamesrajendran/f197931625f7a8daa2354c7ebc60932c to your computer and use it in GitHub Desktop.
Save jamesrajendran/f197931625f7a8daa2354c7ebc60932c to your computer and use it in GitHub Desktop.
Scala examples
map:
val l = List(1,2,3,4,5)
l.map(x => x + 3 ) or l.map(_ + 3 )
pass a function as param to map:
def f(x:Int) = if (x > 3 ) (x) else None
l.map(x => f(x)) or l.map( f(_))
flatMap example:
val l = List(1,2,3,4,5)
def g(v:Int) = List(v-1, v, v+1)
l.map(x => g(x)) or l.map( g(_))
res21: List[List[Int]] = List(List(0, 1, 2), List(1, 2, 3), List(2, 3, 4), List(3, 4, 5), List(4, 5, 6))
l.flatMap(x => g(x)) or l.flatMap( g(_))
res22: List[Int] = List(0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6)
--------------------------reduce---------------------
val numbers = Array(1,2,3,4,5)
numbers.reduceLeft(_+_) equivalent to numbers.reduceLeft((a:Int,b:Int) => a + b)
numbers.reduceLeft(_*_) equivalant to numbers.reduceLeft((a:Int,b:Int) => a * b )
-----------------------------------------------------------------------
Scala functions:
call by name ( t: => Long) (variable name => type)
variable arguments
default parameter values
nested functions
named arguments
recursion functions
higher-order func
anonymous funs
partially applied funcs - Function where some parameter values passed which in turn returns a function with the left out parameter values.
partially defined funcs/partiall Functions
currying funcs
Flavours of Functions
Method - similar to a method in a java class
function - class - mixes with one of the 22 function traits Function0.....Function22
based on number of parameters
inherits methods, apply() being the most important -it's the body of the function with same number of parameters
function literal - anonymous function / alternate syntax for defined function eg: (a: Int, b: Int) => a + b
compiler generates a function object and mixes with one of Function traits, thus inherits apply method
function value - instance of some class that extends Function0...Function22
gets compiled as a class
partially applied func explained;
Some or none of the arguments can be passed in scala functions. Since it cannot create the
result, it will automatically generate a partially applied function using the supplied
arguments and then creates a function value from it. The generated partially applied function
mixes in one of the FunctionN traits, whre N depends on the number of missing function-arguments.
The body of the generated function's apply method is basically the invocation of the original
function's apply method with the supplied arguments completed with the the arguments passed in
to the apply method of the generated partially applied function.
val add = (a: Int, b: Int) => a + b
val inc = add(_: Int, 1)
inc(10) // returns 11
Collections:
List, immutable, Linked List
Array, mutable, flat
Sets, no duplicate values
Maps, unique keys, values need not be unique map==hash tables
Tuples,
option,
Iterator
Closures:
The return value depends on one or more variables declared outside the function,
but within the scope.
Closure is a persistent scope which holds on to local variables even after the code execution has moved out of that block. The scope object and all its local variables are tied to the funtion and will persist as long as that function persists.
This gives us function portability. We can expect any variables that were in scope when the function was first defined to still be in scope when we later call the function, even if we call the function in a totally different context.
Option/Some/None:
is a container for zero or one element of a giventype
an Option[t] can be some[T] or None(a missing value)
equivalent to Oracle nvl()
flip side - exception cannot be kwnow unless Scala Either, Left, Right are used.
Either == Option, Left == None Right=Some, thus exception info can be passed with Left.
val bag = List("1", "2", "foo", "3", "bar")
val sum = bag.flatMap(toInt).sum
Nil/Nothing/Null
Nil - empty list
nothing - helps in providing a return type in abnormal termination or in flow with exception, just a trype, can't be instantiated.
NULL - compatible with Java Null type, inherited from AnyRef
Higher-Order functions
Functions that take other functinos as parameters or whose result is a function or both
for reusuability and composability
Currying functions:
is the process of decomposing a function of multiple arguments into a chained sequence of functions of one argument.
f(a,b,x)
g(x) = x => (b => (a =>f(a,b,x)))
h(b) = b => (a => f(a,b,x))
j(a) = a => f(a,b,x)
def line(a: Int, b: Int, x: Int): Int = a * x + b
def curriedLine(a: Int)(b: Int)(x: Int): Int = line(a, b, x)
def defaultLine(x: Int): Int = curriedLine(1)(0)(x)
defaultLine(5)
Abstract Members
besides method definitions like in java
vals, vars, methods, types can be declared abstract
Partial Funcs:
Case class: http://www.alessandrolacava.com/blog/scala-case-classes-in-depth/
Compiler creates a class and its companion object.
implemets the apply method, that can be used as a factory, can create objects without new <ClassName>
prefixes all arguments with val, so the class is immutable but you get the accessors(can't assign a value)
adds natural implementation of
hashcode, equals, toString, == delegated to equal
generates a copy method to create another from one with missing values
implements the unapply method and hence supports Pattern Matching
unapply method allows deconstruction of case class to extract it's fields, both during pattern matching and as simple expression
allows creating a function with case class args as func args and returns the objec of the class
case class and its companion object are serializable by default.
************** pattern matching (case classes, extractors)*************
case classes, extractors are two pattern matching methods, their combination works well for all cases.
They use apply and unapply methods, apply works like constructor, "case <object>()" uses the unapply to work as deconstructer.
pattern match example:
def oddEven(i:Int):Unit = {
i%2 match {
case 0 => println("even: "+i)
case _ => println("odd: "+i)
}
}
--
def matchTest(x: Int): String = x match {
case 1 => "one"
case 2 => "two"
case _ => "many" }
***************************************fold ************************************
takes two parameters, init value and a function
val ll = List(1,2,3)
ll.fold(200) { (a,b) => a min b }
ll.fold(1) { (a,b) => a * b }
*************************map filter**************************
val x = (1 to 10)
x.reverse.map(x => x-1).filter(x => x%2 == 0).filter(x => x>0)
************************* closures***************************
A function that depends on one or more variables declared outside the function:
val factor = 3
def mulFacotr(i:Int):Int = a * factor
************************************ apply ************************
apply - handy way to close gap between object and function
Every function is an object
instead of saying object.function(4), if we say object(4), the compiler will use the apply method
val f = (x:Int) => x + 1
f.apply(2) or f(2) will give the same result 3(2+1)
Every object is a funstion provided it has an apply method.
object Foo{
val y = 5
def apply(x: Int) = x + y
}
Foo(2) will result int 7
treating an object as a function has usefule usecases.
example factory pattern
apply - to assemble an object from its components
unapply - to decompose an object to its components
******************** Any ************************
root of scala
has methods like != eauals, asInstanceOf, isInstanceOf, toString, hashcode
has subclasses AnyVal, AnyRef
*******************function first class citizens*********************
functions assigned to variables
stored in fields
higher order functions
pass function as parameter
return functions as values
****************************singleton/companion object ****************
A companion object is an object with the same name as a class or trait and is defined in the same source file as the associated file or trait. A companion object differs from other objects as it has access rights to the class/trait that other objects do not. In particular it can access methods and fields that are private in the class/trait.
An analog to a companion object in Java is having a class with static methods. In Scala you would move the static methods to a Companion object.
One of the most common uses of a companion object is to define factory methods for class. An example is case-classes. When a case-class is declared a companion object is created for the case-class with a factory method that has the same signature as the primary constructor of the case class. That is why one can create a case-class like: MyCaseClass(param1, param2). No new element is required for case-class instantiation.
A second common use-case for companion objects is to create extractors for the class. I will mention extractors in a future topic. Basically extractors allow matching to work with arbitrary classes.
methods and values that aren't associated with individual instances of a class belong to Singleton objects.
Singleton objects mostly do not stand alond but instead are associated with a class of the same name. when this happens the singleton object is called companion object and the class is calles companion class
something like static
class name and object name be the same in same file
-----------------------------------trait -----------------------------------------------
for multiple inheritence, similar to java interface, used similar to dependency injection
diamond problem - multiple inheritence getting too complicated
------------------------------ tail recursion ----------------------------
while using recursive functions, it may eat up all the allocated stack space. To avoid this scala provides this mechanism,
- instead of using new stack space, uses the current function stack space.
Requisite - use annotation @annotation.tailrec, recursive call has to be the last line in the function.
----------------------------- implicit paramater ---------------------
If a parameter value is not passed, the given default value will be used.
use implicit keyword to make a value, variable, function implicit
---------------------------- yield --------------------------
values returned from an expression can be sent as collection
[vectors more efficient List, specially when random access/update is required]
---------------------------- auxiliary constructor ------------------------
additional/secondary constructors, overloaded with number of parameters or data types.
---------------------------- create jar and run -----------------
eclipse market place install scala IDE
change scala perspective
create scala project
create class files in src/main/scala folder ----without this gives null pointer exception
install sbt (by downloading and installing sbt)
add to path variable
invoke sbt --downloads further files
move to base folder of the project
create build.sbt file
include
name := "some name"
version := "1.0"
scalaVersion := "2.11.8" -- pass the version of scala being used.
invoke sbt package
jar file will be created in target dir
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment