Introduction of
Scala programming languageas well asSpark Scalavia couples of basic scripts in common use cases. Please check the Main files for more information.
- Scala Coursera - My note/code for Coursera Scala series class
- spark_emr_dev - Demo of submitting Hadoop ecosystem jobs to AWS EMR
- spark-etl-pipeline - Demo of various Spark ETL processes
- utility_Scala - Scala/Spark programming basic demo
- Scala Note - Scala learning note
-
Utility Scala - Scala scripts for utility
-
Spark Scala Demo - Scala spark basic demo
-
Scala basic - variable, data structure
- Scala_basic_demo_3 - Scala basic data structrue :
array, list, tuple, applyfunction, lambdawith them basic. Andmap, exceptiondemo - Immutable & mutable
- UNCHANGED : Immutable
- example :
scala.collection.Immutable - Scala has some Immutable class that java already has
- e.g. : Set, Map
- however, Scala has its own unique Immutable class
- e.g. Seq
- immutable.Seq.LinearSeq uses a lot : Queue, Stack ...
stringbelongs to immutable.Seq.IndexedSeq- there is a SortedMap under Map offering "ordering" feature
- example :
- CAN CHANGED : mutable
- example :
scala.collection.mutable
- example :
- Scala uses "immutable" by default
- For most of the data structure, Scala offers both
immutableandmutableversions
- UNCHANGED : Immutable
- Array
immutablearray- ArrScalaArrayDemoay
- ArrayDemo1
- ArrayDemo2
- Scala
Arraybasic op, properties
- ArrayBuffer
mutablearray, similar asArrayListin java- ArrayBufferDemo1
- Array <--> ArrayBuffer
- ArrayBuffer <--> Java List
- Dimension Array
- Array with N-dimension
- DimensionArray1
- Tuple
- TupleDemo1
- can be recognized as a "container"
- can save various elements with
different/same type - tuple can only save
22 elements as MAX
- List
- ListDemo_1
- ListDemo_2
- ListDemo_3
- Scala_yield_to_List
- Scala list
can storage datadirectly (a object); while in Java, list is an interface, the implementation isArrayList - scala list can save
anytype of elements - if want to get a
null list-> useNil(e.g.val list2 = Nil) - Scala Lists are quite similar to arrays, which means all the elements of a list have the same type - but there are two important differences.
- list are immutable, which means elements of a list cannot be changed by assignment.
- By default, Scala List is
immutable(unchanged) - list is ordering (order matters)
- list adding element :
val list_1 = List(1,2,4,"xxx") val list_2 = list_1 :+ 4
- ListDemo_4
- ListDemo_5
- list adding element via
::,::::::means adding new element to a list- we must put the list on the
rightof::. (i.e. 4 :: list_1) - computing ordering :
from right to list :::means addEVERYelement in list to anulllist- we must put the list on the
right and leftof:::. (i.e. list_1 ::: list_2 ::: list_3)
- list represents a
linked listwhereas arrays are flat. Thetype of a listthat has elements oftype Tis written as List[T].
- Queue
- Map
- Set
collection of unique elements, no ordering, default is hashmap's implementation- Set is
immuatabledefault in Scala, if want mutable, need importscala.collection.mutable.set - SetDemo_1
- SetDemo_2
- SetDemo_3
- JavaSetDemo_1
- Stream
- stream is one kind of the collection that can storgae
unlimitelements. However, the unlimit elements are not showed up at once, but with dynamic space, the last element in stream following thelazystyle (only computed when called) - StreamDemo_1
- stream is one kind of the collection that can storgae
- Scala_basic_demo_3 - Scala basic data structrue :
-
Scala basic - operation
- map (op)
- FlatMap
- flatMap will go to
every sub groupin a group and map the operation on each of them then return the result - FlatMapDemo_1
- flatMap will go to
- Filter
- Reduce
- Fold
- Enumeration - Scala
Enumerationbasic op, properties - Nothing_demo1, Nothing_demo2 -
Nothingcan still pass information when the program failed. null can be passed to AnyRef, but NOT AnyValue (AnyValue : Int, Float, Char, Boolean, Long, Double, Byte, short...) - Either, Left, Right
- Loop
-
Scala basic - function, class, case class, constructor...
-
Class
- Class - Scala
classbasic op, properties - ClassDemo1
- ClassDemo2
- Method create
class instancein Scala
- Class - Scala
-
Case class
- Case Class
- Case Class2
- Case Class3 - pattern match example
- Case Class4 - copy method demo
- Case Class5 - Pattern match : case class nested structure,
@notation (wrap values in case class to variable) - Case Class6 - Pattern match : case class nested structure 2
- Case Class7 - case class enumeration
- Case Class8 - case class enumeration
- Case Class9 - case class with user defined class
- case class is still class
- decorate class via case
- for
pattern matchpurpose - it offers
applymethod so we don't need tonewcase class (instantiate), but can use it directly - it offers
unapplymethod sopattern matchcan work - will implement some methods by default : e.g. apply, unapply, toString, copy, hashCode....
- Difference between
classandcase class- =>
case classcan initiateattr, value, structurewhen instantiated
- =>
- it's not necessary that case class to inherent from other class
- apart from above, case class is as same as class, we can extend, rewrite it
- implements
serializationby default - implements
applymethod by default
-
Sealed class
- Seal demo 1
- sealed class can only be extended in the
same class/object
-
ClassPolymorphismDemo1 - Scala class
PolymorphismDemo -
ScalaDefaultValueDemo1 - Scala Scala Default Value
-
ScalaIfElseMatchForloop - Scala
if, else, while, matchbasic -
Function
- ScalaFunction_1 - Scala
function, lambdabasic - ScalaFunction_2 - Scala
function with dynamic var length
- ScalaFunction_1 - Scala
-
Scala_basic_demo_4 - Scala
try, exception,error handlingdemo -
ScalaFileIODemo, ScalaFileIODemo2, ScalaFileIODemo3 - Scala file IO basic
-
ScalaLazyDemo - Scala lazy value demo
-
ScalaUnitDemo - Scala function with
no return valuecalled asprocedure, with return typeUnit -
Override
- OverrideDemo
- OverrideDemo2
- OverrideDemo3
- OverrideDemo4
- OverrideDemo5
- Scala
Overridebasic op, properties
-
Higher Order function
- HigherOrderfuncDemo
- HigherOrderFuncDemo_2
- HigherOrderFuncDemo_3
- HigherOrderFuncDemo_4
- HigherOrderFuncDemo_5
- HigherOrderFuncDemo_6
- HigherOrderFuncDemo_7
Higher Order Functionsare functions that take functions as arguments and/or return functions.
-
Closure
- closure_demo1
- Closure is a combination of a func and its relative references
- Benefit : can reuse the argument in method, so we don't need to re import same arguments everytime when a run the method
- pattern
// pattern def minusxy(x: Int) = { (y: Int) => x - y // anonymous func }
-
Curry
- Curry_demo1
- Curry_demo2
- be able to read it is enough, no need to spend too much time
-
Control Abstract
-
RecursionDemo - Scala
Recursionbasic op, properties -
Constructor
- Constructor can define value to its attribution when create the object
- can has as many as posssible constructor methods in scala
- "main constructor", "support constructor"
- scala constructor format
class ClassName{parameters}{ // main constructor // code // def this(parameters){//support constructor } def this(parameters){// can have multiple support constructors ... } }
-
Patternmatch
- PatternmatchDemo
- PatternmatchDemo2
- PatternmatchDemo3
- PatternmatchDemo4 - Pattern guards demo
- PatternmatchDemo5 - pattern match variable
- PatternmatchDemo6 - match type, can compare
typein pattern match - PatternmatchDemo7 -
case _within match - PatternmatchDemo8 - Pattern match : Array
- PatternmatchDemo9 - Pattern match : List
- PatternmatchDemo10 - Pattern match : tuple
- PatternmatchDemo11 - Pattern match : with for loop
- PatternmatchDemo12 - Pattern match with "Infix notation" (e.g. :
element1 :: element2) - PatternmatchObject - Pattern match on
apply, unapply-> return the object argument that passing into object - PatternmatchObject2
- note : if case objectCollector (
Names(first, second, third)) has multiple arguments -> will callunapplySeqby default
- note : if case objectCollector (
- PatternmatchValueCompare
- Pattern guards ref
- Pattern guards are simply boolean expressions which are used to make cases more specific. Just add if
<boolean expression>after the pattern.
- Pattern guards are simply boolean expressions which are used to make cases more specific. Just add if
- if
compare in a range-> usepattern guards
def showImportantNotification(notification: Notification, importantPeopleInfo: Seq[String]): String = { notification match { case Email(sender, _, _) if importantPeopleInfo.contains(sender) => "You got an email from special someone!" case SMS(number, _) if importantPeopleInfo.contains(number) => "You got an SMS from special someone!" case other => showNotification(other) // nothing special, delegate to our original showNotification function } }
- pattern match variable : can get variable in pattern match -> can be used in next steps op
- Note : if there is a
case _exists in the middle of match -> meaning the pattern match will NOT to compare the value, but still do the type compare. (this case isNOTmatch any case) - example:
val result = obj match{ case a: Int => a // NOTICE here case _ => Int.MaxValue }
-
This
-
Some
- SomeDemo
- Scala
Somebasic op, properties
-
CaseHeadTailNil - Scala
Case on List Head Tail Nilbasic op, properties -
TryGetOrElse, TryGetOrElse2 - Scala
try GetOrElse(else)example -
UpperCass - Scala
UpperCass ( <: )basic op, properties -
Find - Scala
Find,exists,contains, andisDefinedexamples -
Partial Function
- PartialFunc_1
- PartialFunc_2
- Partial applied functions demo 1
- Partial functions demo 1
- can match some conditions, but not do logic operation for every conditions
- example:
// V1 // Any : input type (in this example) // Int : output type (in this example) val addOne_2 = new PartialFunction[Any, Int] { override def isDefinedAt(any: Any): Boolean = { if (any.isInstanceOf[Int]) true else false } override def apply(any: Any) = { any.asInstanceOf[Int] + 1 } } val ans1 = List(1,2,3,4,"ABC").collect(addOne_2) // V2 def f2:PartialFunction[Any, Int]{ // NOTE : we need this : PartialFunction case i:Int => i + 1 // case can transform to partial func automatically } val ans2 = List(1,2,3,4,"ABC").collect(f2) // V3 val ans3 = List(1,2,3,4,"ABC").collect{case i:Int = > i + 1}
- can only do op in specific cases or defined variable type
- In scala, Partial func is the subclass of trait : PartialFunction
-
Anomaly Func
- anomaly_func1
- output type : can only use "type inference"
- use "{}" if code body has multiple lines
-
Type Inference
- typeInference_1
- argument type can be neglected if type is inferenced
- when there is only one argument, we can neglect the
() - if the argument only shows once after
=>, we can use_as argument
-
Bean
- Bean Property -
@BeanPropertyexample
- Bean Property -
-
Type Convert
- TypeConvert1
- TypeConvert2- Scala type convert :
upper transform, lower transform: asInstanceOf, check if object's class type : classOf, getClass.getName
-
example
// *** declare a Employer_03 instance, but transform it to Person_03 class val emp:Person_03 = new Employer_03 // *** transform emp to Employer_03 class (asInstanceOf) emp.asInstanceOf[Employer_03].sayHello() // downward transform
-
SuperConstruct, SuperConstruct1 java, SuperConstruct2, SuperConstruct3- Scala/Java Super constructor examples
-
Operator
-
-
Scala trait, abstract class..
- Trait
- Trait
- TraitAbstract
- TraitDemo2
- TraitDemo3
- TraitDemo4
- TraitDemo5
- TraitDemo6
- TraitDemo7
- TraitDemo8
- TraitDemo9
- TraitDemo10
- Compare the ordering with trait construct ways
- way 1) create class instance -> class hasn't been created yet when mixing trait
- way 2) create "anonymous" sub class -> class already been created when mixing trait
- Compare the ordering with trait construct ways
- TraitDemo11
- TraitDemo12
- TraitDemo13
- TraitAsInterface
- TraitAbstractOverwrite1
- Scala trait : a "supplement" of scala Inheritance (scala only allows "single Inheritance", e.g. a class can only have
one parent class), so trait offers more flexibility - Scala trait can do sth like "java interface"
- trait can have both
abstract method and regular method(a method thatNot implementedin trait is the "abstract" method) - ALL
Java interfacecan be used in scala asScala trait - if there are "composition" traits (
class className extends trait1 with trait2 with trait3 ...) when creating, then scala will- declare the
instancefromleft to right - execute the
methodfromright to left
- declare the
- Scala
TraitDemo,Trait Abstractbasic op, properties. NOTICE :Scala traits don’t allow constructor parameters(so that's why we use abstract class) - pattern
// if no parent class class className extends trait1 with trait2 with trait3 ... // // if there is parent class class className extends parentclassName with trait1 with trait2 with trait3 ...
- TraitMixin1
- TraitMixin2
- TraitMixin3
- TraitMixin:
- Can
mixintraitwhen construct the object(class) => to extend functionality - also can implement on abstract class
- TraitMixin only works in Scala (not Java)
- Can do the extension but not change inheritance status
- Can
- Abstract Class
- Abstract Class
- AbstractDemo
- Scala also has a concept of an abstract class that is similar to Java’s abstract class. But because traits are so powerful, you rarely need to use an abstract class. In fact, you only need to use an abstract class when:
- You want to create a base class that requires constructor arguments
- Your Scala code will be called from Java code
- Class VS Object 1, Class VS Object 2 - Compare Class, object difference, feature in Scala
- Type Parameterlization Demo1 - Type Parameterlization in Scala
- Apply
- Apply method demo 1
- Apply method demo 2
- Apply method demo 3
- Apply method demo 4
- Apply method demo 5
- via
applymethod in the object, one don't need to useobject.apply(sth)for calling the method, but can useobject(sth)directly - if we have 1 object :
Object(param1, param2...)then we will get theCompanion classobject return via theApplymethod
- anonymousClass
- anonymousClass_java
- anonymousClass- *** Override/implement abstract
attribution/method..in java & scala
- Nest class
- NestedClass1
- NestedClass2
- NestedClass3
- is similar as
inner classin java. - definition : if one completed class is inside the other class => nest class
// java example 1 class Outer{ // outer class class inner{ // inner class // code } } class Other{ // outer other class // code }
// java example 2 class OuterClass{ // outer class class InnerClass{ // inner class publice void test (InnerClass ic){ System.out.Prlintln(ic); } } static class StaticInnerClass { // static inner class // code } }
- Trait
-
Scala object
-
LoadPackageDemo1, LoadPackageDemo2, LoadPackageDemo3, LoadPackageDemo4 - Scala load package examples
-
pkgObject -
packagecan have class, object, and trait... but it CAN'T HAVEfunction,var... In order to solve it, scala offers thepackage objectconcept -
Singleton pattern
- Only allow some classes be existing in some specific class instances
- -> pros : can save resources
- -> cons : Thread safety concern
- example :
Runtime classin java - ref Java1
- SingletonDemo java
- SingletonDemo1
- SingletonDemo2
- Only allow some classes be existing in some specific class instances
-
Companion
- CompanionDemo1
- CompanionDemo2
- CompanionDemo3
- CompanionDemo4
- CompanionDemo5
- Companion is the combinaton of
class static method/value..+class basic method/value.. - Scala Companion demo (An object that has the same name as a class is called a companion object of the class, and it is often used to contain factory methods for the class that it complements)
- Since there is no
staticclass/method.. in Scala, so Scala offers the Companion for similIar functionality - In development, we put the basic attribution, method ... in Companion class ; and we put the static consents in the Companion object
-
VisibilityDemo1 - extend package visibility. e.g. :
private[ScalaBasic] val name = "jackkkk" -
ImportPackage1 - Scala import package demo
-
-
Scala implicit
- implicit is the way that you dont need to pass parameters explicitly in functions in Scala, but Scala will be able to find them from the implitict scope once you defined them. Use implicit can make your function more general and easy to import/deal with different cases per pattern
- Implicit_Demo1
- Implicit_Demo2
- Implicit_Demo3
- Implicit_Demo4 : implicit parameter
- Implicit_Demo5
- Implicit_Demo6
- Implicit_Demo7
- Implicit_Demo8
- Implicit_Demo9
more implicit demos- Implicit_1
- Implicit_2
- Implicit_3
- Implicit_4 -
implicit classdemo- More implicit demos from utube tutorial
- implicit func ONLY ACCEPTS ONE ARGUMENT
- the implicit func will BE USED AUTOMATICALLY WHEN THERE IS SUCH CASE
- the NAME of implicit func IS NOT MATTER;
INPUT AND OUTPUT DTYPEIS THE (IMPORTANT) THING - there can be multiple implicit func, but have to make sure THERE IS ONLY ONE implicit func CAN BE REFERRED IN CURRENT STATE
- Note : implicit CAN'T IN "NEST" FORMAT (e.g. one implicit in the other implicit)
- AVOID the case : "FAILED TO FIND IMPLICIT IN CURRENT FIELD, THEN SEARCH ALL POSSIBILITIES (same type) IN THE SPACE"
- implicit_transformation_demo_1, implicit_transformation_demo_2 - implicit transformation can automatically transform "high accuracy" val to "low accuracy". e.g. : Byte -> Short, Short -> Int, Int -> Long, Long -> Float, Char -> Int ..
- ImplicitParameters, ImplicitFunc, ImplicitClass - Scala
implicitin Parameters, func, class
-
Scala OOP
-
Features :
Encapsulation,Inheritance,Polymorphism -
encapsulationDemo1, encapsulationDemo2
- encapsulation is one of the features in OOP, abstract the data and methods and encapsulate them, so only the "defined" method can be implimented to the data
- Pros on encapsulation
- hide the implementation details
- validate the data, make it safe and feat the business needs
- Steps do encapsulation:
- step1) "private" the method/attributions
- step2) offer "public" methods (e.g. :
getter,setteror@BeanProperty...) (getter : set attribution value, getter : get attribution value)
-
-
Scala advance
- Package object
- Parallel
- parallel_Demo_1
- Scala offers the
parallelcollections that can be processed inparallelwith machines have multi-core CPU
- Generic / General Class
- Generic_Demo_1
- Generic_Demo_2
- Generic_Demo_3
- Generic_Demo_4
- Generic_Demo_5
- GenericTypeParam - Scala
Generic Typebasic op, properties, e.g. :def exec[T](f: () => T): T = {f()} - GeneralClass1
- GeneralClass2
- Generic1
- Scala has
Genericinclass, func, method - generic classes
Generic classesare classes which take a type as a parameter. They are particularly useful for collection classes.<:means the type of generic must be "some type" or "some type's" child class:>means the type of generic must be "some type" or "some type's" parent class- Ref
- Upper bounds
- Lower bounds
- View bounds
- ViewBounds1
- 3 view bounds examples
- ViewBounds1
- Context bounds
- ContextBound1
- Context bound examples
- ContextBound1
- Covariant Contravariant Invariant
- CovariantContravariantInvariant
- Covariant Contravariant Invariant demo
- CovariantContravariantInvariant
- MapReduce
-
Scala
Design Pattern-
Decorator
- DecoratorDesignPattern - Scala
Decorator Design Patternexample
- DecoratorDesignPattern - Scala
-
Factory
- Abstract the implemented classes, and put them into a class for better code maintenance, and management.
- We
DON'T instantiatethe subclass directly, but weinstantiateitsfactory. - 3 types of factory
- simple factory
- factory method
- abstract factory
- Simple Factory
- Factory Method
- FactoryMethodDemo1
- Make instantiate methods as abstract methods, and implement in subclass
- Define the abstract method for instantiating object, and let subclass decide with class need to instantiate
Delay class instantiation to subclass
- Abstract Factory
- AbstractFactoryDemo1
- Define a
traitfor creating relative dependent class - Integrate
Simple FactoryandFactory method - an improvement on
Simple Factory(design) - Abstract the factory to
2 layersAbsFactoryActualImplementSubcass
- Singleton
- SingletonDesignPattern1
- Make sure
THERE IS ONLY 1 INSTANCEin the software system - Use cases
- SessionFactory in Hibernate
- ActorSystem in Akka
- Decorator
- Decorator1
- OverseverPattern1
- DecoratorDesignPattern
- Dynamically extend the features to new instances
- Implement the
Open-Closed Principle (OCP)
- Observer
- Proxy
- ProxyDesignPattern1
- ProxyDesignPattern2 : Remote Proxy -- RMI demo (remote method invocation)
- remote-method-invocation-in-java
- RMI : via OOP, doing remote call (method)
- DynamicProxy1
- dynamic_proxy pic
- why
dynamic proxy?- we don't want app access realObject instance directly, so we use dynamic proxy
- proxy + InvocationHandler as proxy role
- dynamic proxy can be multiple combinations per case
- summary :
-
- a proxy instance represents real obj instance
-
- control above via "relection mechanisms"
-
-
-
Scala Script example
- DirectoryOP - Scala
Directory OPexample - Show run time elapse - show how long the code running in Scala
- Scala CLI args
- ScalaGetArg1
- ScalaGetArg2
- ScalaGetArg3
- ScalaGetArg4
- Scala load arguments from CLI
- DirectoryOP - Scala
-
Scala exception, error handling
- ExceptionDemo1
- ExceptionDemo2 - format :
try - catch - finally -
- there is NO
compile exceptionin Scala (only java has), all exceptions in Scala happen duringruntime. All exceptions inherit from the "throwable" class, which is the class with "nothing" type that is acceptable toall class/method...
- there is NO
- ExceptionDemo3
-
Backend framework - Akka
- AkkaDemo1
- AkkaDemo2
- AkkaDemo3 : YellowChicken
- AkkaDemo4 : SparkMasterWorker
- High level
- Akka is a framework for concurrent and distributed applications on the JVM.
- Akka supports multiple programming models for concurrency
- Akka offers Scala, Java API
- All we need to implement is :
Actor. Akka framework will take care rest of them
- Main component
- Actor
- In Akka, everything is an Actor (like OOP, everything is an object)
- Actor is for concurrent
- Actor - Actor communication can only via "Mailbox"
- messages are storaged in the
message queue, and will be post into theMailbox - Actor can do
syncorasyncoperation - Actor receives message via
receivemethod
- ActorSystem
- manage/create Actor
- ActorSystem is singleton
- one JVM can only has
oneActorSystem, but it can hasmultiupleActor
- ActorRef
- Actor representation or reference
- message are sent via ActorRef (not Actor)
- Dispatcher message
- message pool
- Follow
FIFO(first in, first out)
- Mailbox
- managed by Akka, not exposed to developer/user
- implement
runnableJVM object
- Actor
- Summary
- Akka will created an Actor Mailbox instance, it's a queue, can get msg from Dispatcher message
- Mailbox implement Runnable trait, it's a thread, will keep running and use Actor's receive method, so when Dispatcher send msg to Mailbox, Actor can get it via its receive method
ActorRef | "HELLO"means send hello msg to A Actor's Mailbox
- Mechanism
// Actor 1 -> Actor 2 Actor 1 -> ActorRef 1 -> Dispatcher message -> Mailbox -> receive (Actor 2) -> Actor 2 // Actor 2 -> Actor 1 Actor 2 -> ActorRef 2 -> Dispatcher message -> Mailbox -> receive (Actor 1) -> Actor 1
- Others
Quick start manually
# DEMO 1) run scala hello world
$ git clone https://github.com/yennanliu/utility_Scala.git
$ cd utility_Scala
$ scala src/main/scala/UtilityScala/HelloWorld.scala
#$ Hello World
# DEMO 2) run scala spark hello world via sbt
$ cd utility_Scala
$ sbt package
$ sbt
# inside sbt console
sbt:Simple Project> run
# [warn] Multiple main classes detected. Run 'show discoveredMainClasses' to see the list
# Multiple main classes detected, select one to run:
# [1] AnonymousFuncDemo
# [2] ClassDemo
# [3] FileIODemo
# [4] ForLoopDemo
# [5] FunctionChangeableParameterDemo
# [6] FunctionCompositionDemo
# [7] HelloWorld
# [8] IfElseDemo
# [9] OperatorDemo
# [10] PatterMatchDemo
# [11] SimpleApp
# [12] Test
# [13] UderDefinedDefaultParamFuncDemo
# [14] UderDefinedFuncDemo
Enter number: 11
# [info] Running SimpleApp
# ...
# >>>>>>>>>>>>>> OUTPUT
# Lines with a: 21, Lines with b: 9
# >>>>>>>>>>>>>> OUTPUT
# ...
# DEMO 3) run scala spark hello world
$ cd utility_Scala
$ sbt clean compile && sbt assembly
$ spark-submit \
--class "SimpleApp" \
--master local[4] \
target/scala-2.11/simple-project_2.11-1.0.jar
# REPL via sbt console
$ sbt
console
scala>
# ✘ yennanliu@MacBook-Pro ~/utility_Scala master ●
# ✘ yennanliu@MacBook-Pro ~/utility_Scala master ● sbt
# [info] Loading settings for project utility_scala-build from plugins.sbt ...
# [info] Loading project definition from /Users/yennanliu/utility_Scala/project
# [info] Loading settings for project utility_scala from build.sbt ...
# [info] Set current project to UtilityScala (in build file:/Users/yennanliu/utility_Scala/)
# [info] sbt server started at local:///Users/yennanliu/.sbt/1.0/server/ff2f518f2235c5fb0743/sock
# sbt:UtilityScala> console
# [info] Starting scala interpreter...
# Welcome to Scala 2.11.8 (OpenJDK 64-Bit Server VM, Java 1.8.0_252).
# Type in expressions for evaluation. Or try :help.
# scala> import slick.driver.H2Driver.api._
# import slick.driver.H2Driver.api._
# scala>
Quick start via java -cp
sbt assembly
export env=dev
# example 1
java -cp \
./target/scala-2.11/utilityscala_2-0.0.1.jar \
LoadConfigsFromEnv.runWithEnv1 \
-Dconfig.resource=application.${env}.conf
# exampl 2
java -cp target/scala-2.11/utilityscala_2.11-1.0.jar ScalaBasic.CaseClass6Quick start via Docker
$ git clone https://github.com/yennanliu/utility_Scala.git
$ cd utility_Scala
$ docker build . -t spark_env
$ docker run --mount \
type=bind,\
source="$(pwd)"/.,\
target=/utility_Scala \
-i -t spark_env \
/bin/bash
Quick start via `Spark-submit`
# package the scala saprk scripts
$ sbt package
# list the current classes
$ ls target/scala-2.11/classes
# run ForLoopDemo
$ spark-submit \
--class ForLoopDemo \
target/scala-2.11/utilityscala_2.11-1.0.jar
# run LambdaFuncDemo
$ spark-submit \
--class LambdaFuncDemo \
target/scala-2.11/utilityscala_2.11-1.0.jar
# run spark_basic_demo_4
$ spark-submit \
--class SparkBasic.spark_basic_demo_4 \
target/scala-2.11/utilityscala_2.11-1.0.jar
# run MovieSimilarities
$ spark-submit \
--class SparkBasic.MovieSimilarities \
target/scala-2.11/utilityscala_2.11-1.0.jar 50
-
Trouble shooting
- if facing
Origin location must be absolute error in building a SBT projectlike errors when sbt build (sbt package), try to clean the sbt cache viarm -fr ~/.ivy2(remove entire .ivy2 file), then build the project again - https://www.scala-sbt.org/1.x/docs/Dependency-Management-Flow.html
- if facing
-
Clean cache (sbt) : in case when there is issue build the project via IntelliJ sbt
ls -al
rm .ideascala-learn-material
-
Scala Tutorial
- https://docs.scala-lang.org/tour/basics.html
- https://www.handsonscala.com/index.html
- https://github.com/handsonscala/handsonscala
- https://www.javatpoint.com/scala-tutorial
- https://www.tutorialspoint.com/scala/
- http://www.runoob.com/scala/scala-basic-syntax.html
- https://ithelp.ithome.com.tw/users/20107343/ironman/1301?page=1
- https://www.baeldung.com/scala/category/scala-basics
-
Tour on Scala
-
Scala Stadard Library API
-
Scala on stackoverflow
-
Scala Quick Ref
-
Scala books
-
Scala trait intro
Ref
-
Scala
Regular Expression -
Build Scala Spark project with sbt
-
sbt manual
-
Write test for Scala
-
scala test
-
Scala spark source code tutorial
-
Kafka with scala spark demo
-
Spark scala test
-
Spark scala tutorial
-
Scala DB client API
