Skip to content

Instantly share code, notes, and snippets.

@LearningJournal
Last active October 7, 2019 04:49
Show Gist options
  • Save LearningJournal/159af0e44cd1899c5e03f44db01a3f5b to your computer and use it in GitHub Desktop.
Save LearningJournal/159af0e44cd1899c5e03f44db01a3f5b to your computer and use it in GitHub Desktop.
This gist exceeds the recommended number of files (~10). To access all files, please clone this gist.
#!/bin/bash
SBT_OPTS="-Xms512M -Xmx1536M -Xss1M -XX:+CMSClassUnloadingEnabled"
java $SBT_OPTS -jar `dirname $0`/sbt-launch.jar "$@"
chmod a+x /usr/local/bin/sbt
set name:= "HelloScala."
show name
set name:= "HelloScala."
show name
name := "HelloScala."
version := "1.0"
scalaVersion := "2.11"
libraryDependencies += "org.apache.spark" % "spark-core_2.11" % "2.0.2"
val h = "Hello Scala!"
println(h)
class Test {
val s = "Hello Scala!"
}
val t = new Test
println(t.s)
import org.apache.spark.SparkContext
set libraryDependencies += "org.apache.spark" % "spark-core_2.10" % "2.0.2"
def fun(x:Int) = x + 4
def fac(n: Int) = if (n == 0) 1 else n * fac(n - 1)
i.*(5)
i.>(5)
i.abs
i.compare(15)
i + 15
i * 5
i > 5
i compare 5
i compare 15
tar -zxvf scala-SDK-4.5.0-vfinal-2.11-linux.gtk.x86_64.tar.gz -C /usr/local/
<object><method><parameter>
<object><method> (<parameter-1> [, <parameter-2>, ...] )
val s = "my name is ..."
s toUpperCase
s.toUpperCase
def functionName ([<parameterName> :<type> [, ....]]) : [return type] = {
<function body>
return [expr]
}
mkdir -p ~/.sbt/0.13/plugins/
def myMax(x: Int, y: Int): Int = {
if (x > y)
return x;
else
return y;
}
['^(([^<>()[\]\\.,;:\\s@\"]+(\\.[^<>(),[\]\\.,;:\\s@\"]+)*)',
'|(\\".+\\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.',
'[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\\.)+',
'[a-zA-Z]{2,}))$'].join('')
def myMax(x: Int, y: Int): Int = {
if (x > y)
x
else
y
}
//I can squeeze it further like this.
def myMax(x: Int, y: Int): Int = {
if (x > y) x else y
}
def myMax(x: Int, y: Int): Int = if (x > y) x else y
def myMax(x: Int, y: Int) = if (x > y) x else y
def myMax(x:Int, y:Int) = { if (x > y) x else y }
def hWorld() = println("Hello World!")
//String value
val s = "Hello World!"
// Integer value
val l = 5
vi ~/.sbt/0.13/plugins/plugins.sbt
val l: Long = 5
//Another alternative for enforcing the data type is this.
val l = 5: Long
([<parameterName> :<type> [, ....]]) => {
<function body>
return [expr]
} : [return type]
//Compare it with standard def syntax for a Scala function
def functionName ([<parameterName> :<type> [, ....]]) : [return type] = {
<function body>
return [expr]
}
val f = (x:Int) => { x + 5 }
val f = (x:Int) => { x + 5 }:Int
val f:Int => Int = (x:Int) => { x + 5 }
myFun(5,"-")
//should return -5-
val myFun:(Int, String) => String = (x:Int, s:String) => { s + x + s }:String
val myFun = (x:Int, s:String) => { s + x + s }
val customers = List( "donald", "angela","larry","narendra", "vladimir")
(x:String) => x.capitalize
addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "5.1.0")
customers.map((x:String) => x.capitalize)
val data = List(-250, 75, 145 ,222 ,-80 ,-140 , 170 , 85 , 122, 250)
data.map( (x:Int) => 1d*(x-data.min)/(data.max-data.min)*1d)
val r = 1 to 10
r.map(x => x + 10)
r.reduce((x,y) => x + y )
r.reduce((x, y) => x * y)
r.reduce((x, y) => x max y)
r.reduce((x, y) => x + y / x min y)
r.map(x => x + 10)
r.reduce((x, y) => x * y)
r.map(x + 10)
r.reduce(x * y)
r.map(_ + 10)
r.reduce(_ * _)
r.reduce( _ * _ )
mkdir -p TestEclipse/src/main/scala
cd TestEclipse
vi src/main/scala/TestEclipse.scala
//Copy and Paste the below code in your TestEclipse.scala file
object TestEclipse {
def main(args: Array[String]): Unit = {
println("Hello, World! from SBT")
}
}
r.filter(x => x > 5)
r.filter(_ > 5)
r.reduce((x,y) => x + y / x min y)
val f = (x:Int) => x + 10
val f1 = new Function1[Int, Int] {
def apply(x: Int): Int = x + 10
}
import scala.io.Source
import scala.io.Source._
def getErrors(fileName: String) = {
def isError(line: String) = {
if (line.contains("error")) true else false
}
val f = Source.fromFile(fileName)
for (l <- f.getLines() if isError(l)) yield l
}
getErrors("/root/mylog.dat") foreach println
val f2 = f1(5)
/*Output
SQRT of 5 is 2.23606797749979
f2: Int => Double = <function1>
*/
f2(20)
//res0: Double = 5.0
def f1(x: Int) = {
println(s"SQRT of $x is " + Math.sqrt(x))
(y: Int) => Math.sqrt(x + y)
}
val f1 = (x: Int) => {
println(s"SQRT of $x is " + Math.sqrt(x))
(y: Int) => Math.sqrt(x + y)
}
def f1(x: Int) = {
println(s"SQRT of $x is " + Math.sqrt(x))
def f2(y: Int) = Math.sqrt(x + y)
}
/* Output - It return a Unit
f1: (x: Int)Unit
*/
//You can still return an ordinary local function, but you have to do some extra work.
def f1(x: Int) = {
println(s"SQRT of $x is " + Math.sqrt(x))
def f2(y: Int) = Math.sqrt(x + y)
f2 _
}
vi build.sbt
//Copy and paste below content into your build.sbt file
name := "TestEclipse"
version := "1.0"
scalaVersion := "2.11.8"
publishMavenStyle := false
libraryDependencies += "org.apache.spark" % "spark-core_2.11" % "2.0.2" notTransitive ()
EclipseKeys.withJavadoc := false
EclipseKeys.withSource := false
val f2 = f1(3)
def f1(x: Int) = {
println(s"SQRT of $x is " + Math.sqrt(x))
(y: Int) => Math.sqrt(x + y)
}
def f1(x: Int) = { (y: Int) =>
Math.sqrt(x + y)
}
def f1(x:Int) = (y:Int) => Math.sqrt(x+y)
val f1 = (x:Int) => (y:Int) => Math.sqrt(x+y)
val f1: Int => (Int => Double) = (x:Int) => (y:Int) => Math.sqrt(x+y)
val fs:String => (String => String) = (prefix: String) => (s: String) => prefix + " " + s
val fs = (prefix: String) => (s: String) => prefix + " " + s
val fs = (prefix: String) => { (s: String) => prefix + " " + s }
fs("Hi")("There")
val fs = (prefix: String) =>{ () => prefix + " " + "There" }
def intDecorator(x:Int, f: Int => String) = f(x)
intDecorator(5, (y:Int) => "[" + y + "]" )
intDecorator(5, (y:Int) => "<b>" + y + "</b>" )
intDecorator(5, "[" + _.toString + "]" )
def echo(s:String*) = s foreach println
echo("One","Two","Three")
echo("One","Two","Three", "Four", "Five")
Math.sqrt(4.0)
def echo(s:String*, i:Int) = s foreach println
def doSomething(f: String => Unit, s:String) = f(s)
doSomething(x =>println("[" + x + "]") , "Hi There!")
doSomething("Hi There!", x =>println("[" + x + "]") )
doSomething(s="Hi There!", f = x =>println("[" + x + "]"))
def doSomething(f: String => Unit=println, s:String) = f(s)
doSomething(s="Hi There!")
def div(x:Double, y:Double):Double = x/y
def add(x:Double, y:Double):Double = x+y
def inv(y:Double):Double = 1.0/y
def inc(y:Double):Double = 1 + y
var g = 10
//Consider that g is a global variable.
def rt(i: Int): Int = {
g = i + g;
return g
}
//The rt is a function. That's Scala syntax to define a function.
//I am using this function like this.
val v1 = rt(5)
val v2 = rt(5)
def div(x:Double, y:Double):Double = x/y
div(1, _:Double)
val inv = div(1, _:Double)
def sumOfX(f: Int => Int, a: Int, b: Int): Int =
if (a > b) 0 else f(a) + sumOfX(f, a + 1, b)
sumOfX(x => x, 1, 5)
sumOfX(x => x * x, 1, 5)
sumOfX(x => x * x * x, 1, 5)
val sumOfCubes = sumOfX(x => x * x * x, _: Int, _: Int)
sumOfCubes(1, 5)
def applySums(f: (Int, Int) => Int) =
println("I am applying sum of 1 to 5 and the answer is " + f(1, 5))
val x = doThis(a)
.thenThis(b)
.andThenThis(c)
.doThisToo(d)
.andFinallyThis(e)
def sum(x: Int, y: Int, z: Int) = x + y + z
val s3 = sum(_: Int, _: Int, _: Int)
val s4 = sum _
def sumOfX(f: Int => Int, a: Int, b: Int): Int =
if (a > b) 0 else f(a) + sumOfX(f, a + 1, b)
def sumOfX(f: Int => Int)(a: Int, b: Int): Int =
if (a > b) 0 else f(a) + sumOfX(f, a + 1, b)
sumOfX(x => x * x * x)(1, 5)
val si = sumOfX(x => x * x * x) _
val si = sumOfX { x =>
println("Cubing")
x * x * x
} _
def test(i: Int): String = {
var s: String = null
if (i == 1)
s = "One"
else
s = "Something else"
return s
}
def testF(i: Int) =
if (i == 1) "One" else "Something else"
def testF(i: Int) =
if (i == 1) "One"
else if (i == 2) "two"
else if (i == 3) "three"
else "Something else"
def doubler(i:Int):Int = {return i * 2}
val i = 5
val s = if (i == 1) "One" else "Something else"
println(if (i == 1) "One" else "Something else")
val i = 5
val s = if (i == 1) "One" else "Something else"
val s = if (i == 1) println("One") else println("Something else")
val s = if (i == 1) 1 else println("Something else")
def matchX(x: Int) = {
x match {
case 1 => println("Case One")
case 2 => println("Case Two")
case 3 => println("Case Three")
case _ => println("Case Default Case")
}
}
def matchX(x: Int) = {
x match {
case 1 => {
println("Case One")
println("Print it again - Case One")
}
case 2 =>
println("Case Two")
println("Print it again - Case Two")
case 3 => println("Case Three")
case _ => println("Case Default Case")
}
}
def matchX(x: Int) = {
x match {
case 1 => "Case One"
case 2 => "Case Two"
case 3 => "Case Thre"
case _ => "Case Default Case"
}
}
val x = 2
val s = x match {
case 1 => "Case One"
case 2 => "Case Two"
case 3 => "Case Three"
case _ => "Case Default Case"
}
println(s)
def loopN(i: Int) = {
var j = 1
while (j <= i) {
println(j)
j = j + 1
}
}
def loopDo(i: Int) = {
var j = 1
do {
println(j)
j = j + 1
} while (j <= i)
}
//Let's assign it to a variable.
val d = doubler(_)
// Now you can use the variable d as it is a function.
d(5)
d(3)
var i = 0
repeat {
println("Values of i is " + i)
i = i + 1
} until (i > 3)
def repeat(body: => Unit)(condition: => Boolean) = {
do {
//body
} while (!condition)
}
def testUntil = {
var i = 0
repeat {
println("Values of i is " + i)
i = i + 1
}(i > 3)
}
def repeat(body: => Unit) = {
def until(condition: => Boolean) = {
do {
//body
} while (!condition)
}
until _
}
import scala.language.reflectiveCalls
def repeat(body: => Unit) = new {
def until(condition: => Boolean) = {
do {
//body
} while (!condition)
}
until _
}
withTextFile(fileLocation) map (doThisWork)
repeat(doThisWork) until (condition)
val l = List("india", "USA", "UK", "china", "russia")
def f1(s: String) = {
println("Printing " + s)
"Returning " + s
}
l.foreach(println)
/*Output
india
USA
UK
china
Russia
*/
l.map(f1)
/*Output
Printing india
Printing USA
Printing UK
Printing china
Printing russia
res7: List[String] = List(Returning india, Returning USA, Returning UK, Returning china, Returning russia)
*/
val r = 1 to 10
r.map(doubler)
def f3(s: String) = s.split(" ")
val l = List(
"India is a multiparty democratic country, USA is two-party democratic country"
)
l.map(f3)
/*output
res8: List[Array[String]] = List(Array(India, is, a, mulyiparty, democratic, country,, USA, is, two-party, democratic, country))
*/
l.flatMap(f3)
/*output
res9: List[String] = List(India, is, a, mulyiparty, democratic, country,, USA, is, two-party, democratic, country)
*/
val l = List("india", "USA", "UK", "china", "russia")
l.withFilter(x => x.startsWith("i")).map(x => x.capitalize)
res10: List[String] = List(India)
l.filter(x => x.startsWith("i")).map(x => x.capitalize)
for ( seq ) yield { expr }
for ( seq ) { expr }
for (i <- 1 to 10) {
statement - 1;
statement - 2;
}
val n = 1 to 5
// n is a Range collection with ten elements.
//Now I can iterate through this collection using a for Loop.
for (i <- n) println(i)
// You can remove the middleman and get a collection on the fly.
for (i <- 1 to 5) println(i)
for (country <- List("India", "USA", "China", "Japan")) {
country match {
case "India" => println("Delhi")
case "USA" => println("Washington D.C.")
case "Japan" => println("Tokyo")
case _ => println("I don't know")
}
}
val countries = List("India","USA","China","Japan")
countries.foreach { country =>
country match {
case "India" => println("Delhi")
case "USA" => println("Washington D.C.")
case "Japan" => println("Tokyo")
case _ => println("I don't know")
}
}
for ( seq ) yield { expr }
val countries = List("India", "USA", "China", "Japan")
for (country <- countries) yield {
country match {
case "India" => "Delhi"
case "USA" => "Washington D.C."
case "Japan" => "Tokyo"
case _ => "I don't know"
}
}
val capitals = for (country <- countries) yield {
country match {
case "India" => "Delhi"
case "USA" => "Washington D.C."
case "Japan" => "Tokyo"
case _ => "I don't know"
}
}
for ( seq ) yield { expr }
for (i <- 1 to 3; j <- 1 to 2) println(s"i=$i j=$j")
/* Output
i=1 j=1
i=1 j=2
i=2 j=1
i=2 j=2
i=3 j=1
i=3 j=2
*/
(i:Int) => { i*2 } :Int
for (i <- 1 to 3; j <- 1 to 2; k <- 1 to 2) println(s"i=$i j=$j k=$k")
for {
i <- 1 to 3;
j <- 1 to 2;
k <- 1 to 2;
} println(s"i=$i j=$j k=$k")
for {
i <- 1 to 3
j <- 1 to 2
k <- 1 to 2
} println(s"i=$i j=$j k=$k")
for {
i <- 1 to 3
j <- 1 to 2; if (j % 2 == 0)
k <- 1 to 2
} println(s"i=$i j=$j k=$k")
for {
i <- 1 to 3
j <- 1 to 2
if (j % 2 == 0)
k <- 1 to 2
} println(s"i=$i j=$j k=$k")
employee_id first_name last_name email phone_number hire_date job_id salary commission_pct manager_id department_id
100 Steven King SKING 515.123.4567 17-JUN-1987 AD_PRES 24000 NULL NULL 90
101 Neena Kochhar NKOCHHAR 515.123.4568 21-SEP-1989 AD_VP 17000 NULL 100 90
102 Lex De Haan LDEHAAN 515.123.4569 13-JAN-1993 AD_VP 17000 NULL 100 90
103 Alexander Hunold AHUNOLD 590.423.4567 03-JAN-1990 IT_PROG 9000 NULL 102 60
104 Bruce Ernst BERNST 590.423.4568 21-MAY-1991 IT_PROG 6000 NULL 103 60
105 David Austin DAUSTIN 590.423.4569 25-JUN-1997 IT_PROG 4800 NULL 103 60
106 Valli Pataballa VPATABAL 590.423.4560 05-FEB-1998 IT_PROG 4800 NULL 103 60
107 Diana Lorentz DLORENTZ 590.423.5567 07-FEB-1999 IT_PROG 4200 NULL 103 60
108 Nancy Greenberg NGREENBE 515.124.4569 17-AUG-1994 FI_MGR 12000 NULL 101 100
109 Daniel Faviet DFAVIET 515.124.4169 16-AUG-1994 FI_ACCOUNT 9000 NULL 108 100
import scala.io._
for (line <- Source.fromFile("employees.csv").getLines().toList) println(line)
for (line <- Source.fromFile("employees.csv").getLines().toList) {
val fields = line.split(",")
println(fields(0) + "--" + fields(1) + "--" + fields(2) + "--" + fields(10))
}
for {
line <- Source.fromFile("employees.csv").getLines().toList
fields = line.split(",")
} println(fields(0) + "--" + fields(1) + "--" + fields(2) + "--" + fields(10))
for {
line <- Source.fromFile("employees.csv").getLines().toList
fields = line.split(",")
if (fields(10) == "60")
} println(fields(0) + "--" + fields(1) + "--" + fields(2) + "--" + fields(10))
val d = (i: Int) => { i * 2 }
//And then, you can call it using the variable.
d(3)
select employee_id, first_name, last_name, department_id
from employees
where department_id=60;
department_id department_name manager_id location_id
90 Administration 200 1700
20 Marketing 201 1800
60 Purchasing 114 1700
40 Human Resources 203 2400
100 Shipping 121 1500
val emp = for {
dept <- Source.fromFile("departments.csv").getLines().toList
deptfields = dept.split(",")
emp <- Source.fromFile("employees.csv").getLines().toList
empfields = emp.split(",")
if (deptfields(0) == empfields(10))
} yield (empfields(0), empfields(1), empfields(2), deptfields(1))
emp foreach println
for ( seq ) yield { expr }
class JCustomer {
//Private properties
private var custID: Int = 0
private var custName: String = null
//Public constructor
def this(id: Int, name: String) {
this()
this.custID = id
this.custName = name
}
//Public getter
def getID() = custID
def getName() = custName
//Public setter
def setID(nID: Int) = custID = nID
def setName(nName: String) = custName = nName
}
val c = new JCustomer(101, "XYZ Corp")
//When you want to read the private field, you will call a getter method.
c.getID()
//When you want to modify the private field, you will call a setter method.
c.setName("XYZ Corporation")
c.getName()
class Customer(var id: Int, var name: String)
val c = new Customer(101, "XYZ Corp")
//But when you want to read the members variables, instead of calling a getter method, you will use them directly.
c.id
c.name
//There is no need to call a getID and getName methods.
//You don't even need the set methods as well. You can directly modify the members.
c.id = 101
c.name = "XYZ Corp"
class JCircle {
//Private field
private var radius = 0
//Constructor
def this(r: Int) {
this()
setRadius(r)
}
//Set method with data validation
def setRadius(r: Int): Unit = {
if (r < 0) throw new Exception("-ive not allowed") else radius = r
}
//Get method
def getRadius() = radius
}
class Circle {
//Private field
private var _pradius = 0
//Constructor
def this(r: Int) {
this()
radius = r
}
//Set method with data validation
def radius_=(r: Int) = {
if (r < 0) throw new Exception("-ive not allowed") else _pradius = r
}
//Get method
def radius = _pradius
}
def getOps(c: Int) = (i: Int) => {
val doubler = (x: Int) => { x * 2 }
valtripler = (x: Int) => { x * 3 }
if (c > 0) doubler(i)
else tripler(i)
}
class Circle { }
class Circle {
var radius = 0
def draw = { println("Drawing the circle of radius " + radius) }
}
val c = new Circle
/*Output
radius radius_=
*/
//But no one calls the writer using this notation. We can simply call it like this.
c.radius = 5
class Circle {
private var p_radius = 0
//TODO: implement reader/writer methods
}
class Circle {
private var p_radius = 0
//Reader
def radius = p_radius
}
class Circle {
private var p_radius = 0
//Reader
def radius = p_radius
//Writer
def radius_=(r: Int) = {
if (r < 0) throw new Exception("-ive not allowed") else p_radius = r
}
def setRadius(r: Int) = {
if (r < 0) throw new Exception("-ive not allowed") else p_radius = r
}
}
val c = new Circle
c.setRadius = 5
c.setRadius(5)
class Circle {
val radius = 0
}
val r = 1 to 10
r.map(getOps(-5))
class Circle {
var radius = 0
}
val c = new Circle()
public class Circle {
//Instance variable
private int radius;
//Constructor
public Circle(int newRadius) {
this.radius = newRadius;
}
//Get and Set methods
public int getRadius() {
return this.radius;
}
public void setRadius(int r) {
this.radius = r;
}
}
class Circle {
//Instance variable
int radius;
//Constructor
Circle(intnewRadius) {
this.radius = newRadius;
}
}
class Circle(var newRadius: Int) {
var radius = newRadius
}
class Circle(var radius: Int)
class Circle(val radius: Int)
class Circle(private val radius: Int)
class Circle(radius: Int)
class Box(var width: Int, var height: Int, var depth: Int) {
//Auxiliary constructors
def this() = {
this(1, 1, 1);
}
def this(w: Int, h: Int) {
this(w, h, 1);
}
def showBox = println(s"width = $width height= $height depth=$depth")
}
def getOps2(c: Int) = (i: Int) => {
if (c > 0) {
i * 2
} else {
i * 3
}
}
val b = new Box()
b.showBox
val b = new Box(5, 3)
b.showBox
val b = new Box(5, 3, 2)
b.showBox
val smallCircle = new Circle(5)
val mediumCircle = new Circle(25)
val largeCircle = new Circle(100)
Console.println(s"${Console.RED}Ha Ha ${Console.RESET} He He..")
import java.util.Calendar
import java.text.SimpleDateFormat
object StaticDateTime {
private val dateFormat = "EEEE, d-MMM-yyyy"
private val timeFormat = "K:m aa z(ZZ)"
def currentDate: String = getCurrentDateTime(dateFormat)
def currentTime: String = getCurrentDateTime(timeFormat)
def dateAdd(date: String, days: Int): String = {
val df = new SimpleDateFormat(dateFormat)
val dt = df.parse(date)
val cal = Calendar.getInstance()
cal.setTime(dt)
cal.add(Calendar.DATE, days)
df.format(cal.getTime())
}
private def getCurrentDateTime(format: String): String = {
val df = new SimpleDateFormat(format)
val cal = Calendar.getInstance()
df.format(cal.getTime())
}
}
//How to Use Scala Object Methods
StaticDateTime.currentDate
StaticDateTime.currentTime
StaticDateTime.dateAdd(StaticDateTime.currentDate, 5)
object TestSingleton {
println("First Use..")
def sayHello = println("Hi there!")
}
TestSingleton.sayHello
//Now try it once again.
TestSingleton.sayHello
TestSingleton.sayHello
//Create a configuration file in current directory
//File Name - config.properties
//Paste below content
dbpassword = dont - tell - password
database = localhost
dbuser = prashant
//Code Example
import java.util._
import java.io._
object appConfig {
private val prop = new Properties();
prop.load(new FileInputStream("config.properties"));
def config = prop
}
//How to use it
appConfig.config.getProperty("dbuser")
appConfig.config.getProperty("database")
object appConfig {
private val prop = new Properties();
prop.load(new FileInputStream("config.properties"));
def apply(s: String) = prop.getProperty(s)
}
//How to use it
appConfig("dbuser")
appConfig("database")
appConfig.apply("dbuser")
appConfig("dbuser")
var customers = Array("Mike", "Zara","Abdul","Peter")
val myList = List("India", "America", "Japan", "China")
myList(0)
myList(2)
myList.apply(2)
class Graph(path: String) {
println("Load the Graph from file")
def numEdges = 506
def numVertices = 305
def persist(storageLevel: Int) = println("Returns a new persisted Graph")
}
val g = new Graph("file_location")
g.persist(Graph.MEMORY_ONLY)
object StorageLevel {
val DISK_ONLY = 0
val MEMORY_ONLY = 1
val MEMORY_ONLY_COMPRESSED = 2
val MEMORY_AND_DISK = 3
val MEMORY_AND_DISK_COMPRESSED = 4
}
val g = new Graph("file_location")
g.persist(0)
g.persist(StorageLevel.MEMORY_ONLY)
val g = new Graph("file_location")
g.persist(Graph.MEMORY_ONLY)
object Graph {
val DISK_ONLY = 0
val MEMORY_ONLY = 1
val MEMORY_ONLY_COMPRESSED = 2
val MEMORY_AND_DISK = 3
val MEMORY_AND_DISK_COMPRESSED = 4
def apply(path: String) = new Graph(path)
}
val g = Graph("file_location")
val g = Graph("file_location")
class Graph private (path: String) {
println("Load the Graph from file")
def numEdges = 506
def numVertices = 305
def persist(storageLevel: Int) = println("Returns a new Graph")
}
object Graph {
val DISK_ONLY = 0
val MEMORY_ONLY = 1
val MEMORY_ONLY_COMPRESSED = 2
val MEMORY_AND_DISK = 3
val MEMORY_AND_DISK_COMPRESSED = 4
def apply(path: String) = new Graph(path)
}
for (i <- 0 to customers.length - 1) {
println("Hi " + customers(i));
}
val myList = List("India", "America", "Japan", "China")
val s = Room(STANDARD)
val d = Room(DELUXE)
val sd = Room(SUPER_DELUXE)
//File Name - hotels.scala
package guru.learningjournal.hotels
abstract class Room {
def bookingPrice: Double
def facilities: List[String]
def availability: Int
def book(noOfRooms: Int)
}
object Room {
val STANDARD = 0
val DELUXE = 1
val SUPER_DELUXE = 2
private class standardRoom extends Room {
private var _availability = 20
override def bookingPrice = 70
override def facilities = List("Queen Bed", "TV", "Chair", "Table", "Fan")
override def availability = _availability
override def book(noOfRooms: Int) = {
_availability = _availability - noOfRooms
}
}
private class DeluxeRoom extends Room {
private var _availability = 10
override def bookingPrice = 90
override def facilities = List("Bed", "TV", "Chair", "Table", "AC")
override def availability = _availability
override def book(noOfRooms: Int) = {
_availability = _availability - noOfRooms
}
}
private class superDeluxeRoom extends Room {
private var _availability = 5
override def bookingPrice = 120
override def facilities =
List("Double Bed", "Single Bed", "TV", "Sofa", "Reading Table", "AC")
override def availability = _availability
override def book(noOfRooms: Int) = {
_availability = _availability - noOfRooms
}
}
def apply(roomType: Int): Room = {
roomType match {
case SUPER_DELUXE => new superDeluxeRoom()
case DELUXE => new DeluxeRoom()
case _ => new standardRoom()
}
}
}
mkdir DemoHotel
cd DemoHotel
vi hotels.scala
vi build.sbt
//paste below code in the build.sbt file
name:= "Demo Hotels"
version := "1.0"
scalaVersion := "2.12.4"
import guru.learningjournal.hotels.Room
import guru.learningjournal.hotels.Room._
val s = Room(STANDARD)
s.bookingPrice
s.availability
def remindPayment(x: String) = println("Payment reminder for " + x)
//Here is my dummy function for payment reminder. The new loop looks like this.
var i = 0;
for (i <- 0 to customers.length - 1) {
remindPayment(customers(i));
}
forEach(customers, remindPayment)
forEach(vendors, sendPayment)
def forEach(a: Array[String], f: String => Unit) = {
var i = 0;
for (i <- 0 to a.length - 1) {
f(a(i));
}
}
customers foreach remindPayment
var s = "Hello World!"
//After initializing it once, you can change it later.
s = "Hello Scala!"
val v = "You can't change me."
//Let me try to reassign it.
v = "Let me try."
sum(3, 1) returns 4
def iFactorial(n: Int): Int = {
var i = n
var f = 1
while (i > 0) {
f = f * i
i = i - 1
}
return f
}
def rFactorial(n: Int): Int = {
if (n <= 0)
return 1
else
return n * rFactorial(n - 1)
}
def eFactorial(n: Int): Int = {
if (n <= 0)
throw new Exception("boom!")
else
return n * eFactorial(n - 1)
}
def tFactorial(n: Int, f: Int): Int = {
println("Calling tFactorial.")
if (n <= 0)
return f
else
return tFactorial(n - 1, n * f)
}
tFactorial(5,1)
def tFactorial(n: Int, f: Int): Int = {
if (n <= 0)
throw new Exception("boom!")
else
return tFactorial(n - 1, n * f)
}
def Factorial(i: Int): Int = {
println("You called Factorial for " + i)
def tFactorial(n: Int, f: Int): Int = {
if (n <= 0)
f
else
tFactorial(n - 1, n * f)
}
return tFactorial(i, 1)
}
println("Hello Scala")
def myResult(m: Int) = {
var r = ""
if (m >= 50)
r = "passed";
else
r = "failed";
println(r)
}
myResult(65)
val x = println("Hello")
def myResult(m:Int) = if(m >= 50) "passed" else "failed"
println(myResult(65))
def Factorial(i: Int): Int = {
println("You called Factorial for " + i)
def tFactorial(n: Int, f: Int): Int = {
if (n <= 0)
f
else
tFactorial(n - 1, n * f)
}
returntFactorial(i, 1)
}
val s = Factorial(15) / Factorial(11)
/*Output
You called Factorial for 15
You called Factorial for 11
s: Int = 50 */
println(s)
println(s)
def twice(i: Int) = {
println("We haven't used i yet")
i + i
}
twice(Factorial(15)/Factorial(11) )
def twice(f: => Int) = {
println("We haven't used f yet")
f + f
}
twice({ Factorial(15) / Factorial(11) })
/*Output
We haven't used f yet
You called Factorial for 15
You called Factorial for 11
You called Factorial for 15
You called Factorial for 11
res2: Int = 100
*/
def twice(f: => Int) = {
val i = f
println("We haven't used i yet")
i + i
}
lazy val l = Factorial(15)/Factorial(11)
def twice(f: => Int) = {
val i = f
println("We didn't use i yet")
i + i
}
twice(Factorial(15)/Factorial(11))
def twice(f: => Int) = {
lazy val i = f
println("We didn't use i yet")
i + i
}
twice(Factorial(15) / Factorial(11))
/* Output
We didn't use i yet
You called Factorial for 15
You called Factorial for 11
res3: Int = 100 */
import scala.io._
val s = Source
.fromFile("error_log")
.getLines()
.toList
.filter(_.contains("[error]"))
.take(2)
s foreach println
val s = Source.fromFile("error_log").getLines().toList
val s = Source.fromFile("error_log").getLines().toStream.filter(_.contains("[error]")).take(2)
s foreach println
def fibFrom(a: Int, b: Int): Stream[Int] = a #:: fibFrom(b, a + b)
val f = fibFrom(1,2)
f.takeWhile(_<10) foreach println
def myTest(x: Any) = {
x match {
case i: Integer => "It's an Integer = " + i
case s: String => "It's an String = " + s
case d: Double => "It's a double = " + d
case _ => "Opps! Somthing Else"
}
}
//Let me test my code.
println(myTest("abc"))
println(myTest(2.5))
println(myTest(2))
println(myTest(1 to 10))
class Message(p_id: String, p_msg: String) {
val id = p_id;
val msg = p_msg;
}
val messageList = List(
Message("tom@gmail.com", "Message text 1"),
Message("7742394590", "Message text 2"),
Message("8326192398", "Message text 3"),
Message("lisa@gmail.com", "Message text 4"),
Message("lisa@yahoo.com", "Message text 5"),
Message("harry@gmail.com", "Message text 6")
)
def testMessagePattern(l: List[Message]): String = {
l match {
case Nil => "Not found"
case Message(EmailAddress(u1, d1), _) :: Message(EmailAddress(u2, d2), _) :: _
if (u1 == u2) =>
u1 + " got two successive emails"
case h :: t => testMessagePattern(t)
}
}
class Message(p_id: String, p_msg: String) {
val id = p_id;
val msg = p_msg;
}
object Message {
def apply(id: String, msg: String) = new Message(id, msg)
def unapply(m: Message): Option[(String, String)] = {
if (m == null) None
else Some(m.id, m.msg)
}
}
object EmailAddress {
def apply(uname: String, dname: String) = uname + "@" + dname
def unapply(str: String): Option[(String, String)] = {
val parts = str split "@"
if (parts.length == 2) Some(parts(0), parts(1)) else None
}
}
def testMessagePattern(l: List[Message]): String = {
l match {
case Nil => "Not found"
case Message(EmailAddress(u1, d1), _) :: Message(EmailAddress(u2, d2), _) :: _
if (u1 == u2) =>
u1 + " got two successive emails"
case h :: t => testMessagePattern(t)
}
}
val messageList = List(
Message("tom@gmail.com", "Message text 1"),
Message("7742394590", "Message text 2"),
Message("8326192398", "Message text 3"),
Message("lisa@gmail.com", "Message text 4"),
Message("lisa@yahoo.com", "Message text 5"),
Message("harry@gmail.com", "Message text 6")
)
println(testMessagePattern(messageList))
def getHike(salary:Double) = salary * p/100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment