# Scala Training Log
# Scala Training Log
~/temp/foo $ sbt
[info] Loading settings for project global-plugins from idea.sbt ...
[info] Loading global plugins from /Users/sanjib/.sbt/1.0/plugins
[info] Loading settings for project foo-build from plugins.sbt,build.sbt ...
[info] Loading project definition from /Users/sanjib/temp/foo/project
[info] Loading settings for project Foo from build.sbt ...
[info] Set current project to Foo (in build file:/Users/sanjib/temp/foo/)
[info] sbt server started at local:///Users/sanjib/.sbt/1.0/server/18
[Foo] $ console
[info] Starting scala interpreter...
Welcome to Scala 2.12.6 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_65).
Type in expressions for evaluation. Or try :help.
// List Manipulation
scala> val l = List(1,2,3)
l: List[Int] = List(1, 2, 3)
scala> l.map(x => x*2)
res0: List[Int] = List(2, 4, 6)
scala> val dl = l.map(x => x*2)
dl: List[Int] = List(2, 4, 6)
scala> case class Emp(name:String, age:Int)
defined class Emp
scala> val l = List(Emp("John", 30), Emp("Jim", 28), Emp("Jack", 32))
l: List[Emp] = List(Emp(John,30), Emp(Jim,28), Emp(Jack,32))
scala> l.map(x => x.name)
res1: List[String] = List(John, Jim, Jack)
scala> l.map(x => x.age)
res2: List[Int] = List(30, 28, 32)
scala> val i = List(1,2,3)
i: List[Int] = List(1, 2, 3)
scala> i.filter(x => x<=2)
res4: List[Int] = List(1, 2)
scala> i.filter(x => x%2==0)
res5: List[Int] = List(2)
scala> i
res6: List[Int] = List(1, 2, 3)
scala> val j = i.filter(x => x%2==0)
j: List[Int] = List(2)
scala> i
res7: List[Int] = List(1, 2, 3)
scala> j
res8: List[Int] = List(2)
scala> l
res9: List[Emp] = List(Emp(John,30), Emp(Jim,28), Emp(Jack,32))
scala> def isEven(x:Int) = x%2 == 0)
<console>:1: error: ';' expected but ')' found.
def isEven(x:Int) = x%2 == 0)
^
scala> def isEven(x:Int) = x%2 == 0
isEven: (x: Int)Boolean
scala> i
res10: List[Int] = List(1, 2, 3)
scala> i.filter(x => isEven(x))
res11: List[Int] = List(2)
scala> l
res12: List[Emp] = List(Emp(John,30), Emp(Jim,28), Emp(Jack,32))
scala> l.filter(e => e.age<=30)
res13: List[Emp] = List(Emp(John,30), Emp(Jim,28))
scala> val m = l.filter(e => e.age<=30)
m: List[Emp] = List(Emp(John,30), Emp(Jim,28))
scala> m.map(x => x.name)
res14: List[String] = List(John, Jim)
scala> val m = l.filter(e => e.age<=30).map(e => e.name)
m: List[String] = List(John, Jim)
scala> val m = l.filter(e => e.age<=30).map(e => e.name).filter(n => n == "Some")
m: List[String] = List()
scala> l
res16: List[Emp] = List(Emp(John,30), Emp(Jim,28), Emp(Jack,32))
scala> i
res17: List[Int] = List(1, 2, 3)
scala> l(2)
res18: Emp = Emp(Jack,32)
scala> l
res19: List[Emp] = List(Emp(John,30), Emp(Jim,28), Emp(Jack,32))
scala> l(0)
res20: Emp = Emp(John,30)
scala> l(1)
res21: Emp = Emp(Jim,28)
scala> l(2)
res22: Emp = Emp(Jack,32)
scala> l.head
res23: Emp = Emp(John,30)
scala> l.tail
res24: List[Emp] = List(Emp(Jim,28), Emp(Jack,32))
scala> l.tail.head
res25: Emp = Emp(Jim,28)
scala> l.tail
res26: List[Emp] = List(Emp(Jim,28), Emp(Jack,32))
scala> l.last
res27: Emp = Emp(Jack,32)
scala> l
res28: List[Emp] = List(Emp(John,30), Emp(Jim,28), Emp(Jack,32))
scala> l.last
res29: Emp = Emp(Jack,32)
scala> l.init
res30: List[Emp] = List(Emp(John,30), Emp(Jim,28))
scala> l.take(2)
res31: List[Emp] = List(Emp(John,30), Emp(Jim,28))
scala> l.take(1)
res32: List[Emp] = List(Emp(John,30))
// Drop
scala> l.drop(2)
res35: List[Emp] = List(Emp(Jack,32))
scala> l
res36: List[Emp] = List(Emp(John,30), Emp(Jim,28), Emp(Jack,32))
scala> l.drop(2)
res37: List[Emp] = List(Emp(Jack,32))
scala> val i = List(1,2,3,4,5,6,7,8,9)
i: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
// Chaining
scala> i.drop(2).take(2)
res38: List[Int] = List(3, 4)
// Take
scala> i.take(5).filter(x => isEven(x))
res39: List[Int] = List(2, 4)
// Functions on List
scala> i.
++ flatMap min sortBy
++: flatten minBy sortWith
+: fold mkString sorted
/: foldLeft nonEmpty span
:+ foldRight orElse splitAt
:: forall padTo startsWith
::: foreach par stringPrefix
:\ genericBuilder partition sum
WithFilter groupBy patch tail
addString grouped permutations tails
aggregate hasDefiniteSize prefixLength take
andThen hashCode product takeRight
apply head productArity takeWhile
applyOrElse headOption productElement to
canEqual indexOf productIterator toArray
collect indexOfSlice productPrefix toBuffer
collectFirst indexWhere reduce toIndexedSeq
combinations indices reduceLeft toIterable
companion init reduceLeftOption toIterator
compose inits reduceOption toList
contains intersect reduceRight toMap
containsSlice isDefinedAt reduceRightOption toSeq
copyToArray isEmpty repr toSet
copyToBuffer isTraversableAgain reverse toStream
corresponds iterator reverseIterator toString
count last reverseMap toTraversable
diff lastIndexOf reverse_::: toVector
distinct lastIndexOfSlice runWith transpose
drop lastIndexWhere sameElements union
dropRight lastOption scan unzip
dropWhile length scanLeft unzip3
endsWith lengthCompare scanRight updated
equals lift segmentLength view
exists map seq withFilter
filter mapConserve size zip
filterNot max slice zipAll
find maxBy sliding zipWithIndex
scala> i
res40: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
scala> i.exists(x => x == 5)
res41: Boolean = true
scala> i.exists(x => x == 51)
res42: Boolean = false
scala> i.exists(x => x > 8)
res43: Boolean = true
scala> i.sum
res44: Int = 45
scala> i.min
res45: Int = 1
scala> i.ma
map mapConserve max maxBy
scala> i.max
res46: Int = 9
scala> i.sorted
res48: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
scala> i.reverse
res49: List[Int] = List(9, 8, 7, 6, 5, 4, 3, 2, 1)
scala> i.exists(x => x > 8)
res50: Boolean = true
scala> val o = Option(2,3)
o: Option[(Int, Int)] = Some((2,3))
scala> val o = Option(2)
o: Option[Int] = Some(2)
scala> o.map(x => x*2)
res51: Option[Int] = Some(4)
scala> o.filter(x => x <3)
res52: Option[Int] = Some(2)
scala> o.filter(x => x <1)
res53: Option[Int] = None
scala> o.exists(x => x > 1)
res54: Boolean = true
scala> o.exists(x => x == 1)
res55: Boolean = false
scala> l.isEmpty
res56: Boolean = false
scala> o.isEmpty
res57: Boolean = false
// Filter
scala> o
res58: Option[Int] = Some(2)
scala> o.filter( x => x ==3)
res59: Option[Int] = None
scala> o.filter( x => x ==3).isEmpty
res60: Boolean = true
scala> i
res61: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
// Find
scala> i.find(x => x == 5)
res62: Option[Int] = Some(5)
scala> i.find(x => x == 51)
res63: Option[Int] = None
scala> i.find(x => x == 5
| )
res64: Option[Int] = Some(5)
scala> i.find(x => x == 5).get
res65: Int = 5
scala> i.find(x => x == 51).get
java.util.NoSuchElementException: None.get
at scala.None$.get(Option.scala:349)
at scala.None$.get(Option.scala:347)
... 36 elided
scala> i.find(x => x == 51).isDefined
res67: Boolean = false
scala> i.find(x => x == 51).isEmpty
res68: Boolean = true
scala> i.find(x => x == 5).isEmpty
res69: Boolean = false
scala> i.find(x => x == 5).isDefined
res70: Boolean = true
scala> i.find(x => x == 5).get
res71: Int = 5
scala> i.find(x => x == 5)
res72: Option[Int] = Some(5)
scala> i.find(x => x == 5).get
res73: Int = 5
scala> i.find(x => x == 51).get
java.util.NoSuchElementException: None.get
at scala.None$.get(Option.scala:349)
at scala.None$.get(Option.scala:347)
... 36 elided
scala> i.find(x => x == 51).getOrElse(10)
res75: Int = 10
scala> i.find(x => x == 5).getOrElse(10)
res76: Int = 5
scala> i.find(x => x == 5).get
res77: Int = 5
scala> l
res78: List[Emp] = List(Emp(John,30), Emp(Jim,28), Emp(Jack,32))
scala> l.find(e => e.name == "John")
res79: Option[Emp] = Some(Emp(John,30))
scala> l.find(e => e.name == "John").get
res80: Emp = Emp(John,30)
scala> l.find(e => e.name == "John").get.age
res81: Int = 30
scala> i
res82: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
scala> i.filter(x => x % 2 ==0)
res84: List[Int] = List(2, 4, 6, 8)
scala> i
res85: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
scala> i.filter(x => x % 2 ==0)
res86: List[Int] = List(2, 4, 6, 8)
scala> i.find(x => x % 2 ==0)
res87: Option[Int] = Some(2)
scala> i.filter(x => x % 2 ==0)
res88: List[Int] = List(2, 4, 6, 8)
scala> i.find(x => x % 2 ==0)
override def find(p: Int => Boolean): Option[Int]
scala> i.reverse.find(x => x % 2 ==0)
res89: Option[Int] = Some(8)
scala> i
res90: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
scala> i.reverse
res91: List[Int] = List(9, 8, 7, 6, 5, 4, 3, 2, 1)
scala> i.reverse.find(x => x % 2 ==0)
res92: Option[Int] = Some(8)
scala> i.find(x => x % 2 ==0)
res93: Option[Int] = Some(2)
scala> i.find(x => x % 2 ==0)
res94: Option[Int] = Some(2)
scala> val mayBeThere = i.find(x => x % 2 ==0)
mayBeThere: Option[Int] = Some(2)
scala> val mayBeThere = i.find(x => x % 2 ==0)
mayBeThere: Option[Int] = Some(2)
// match
scala> if(mayBeThere.isDefined) println("got "+ mayBeThere.get) else println("Not got")
got 2
scala> mayBeThere match {
| case Some(x) => println("got " + x)
| case None => println("Not got")
| }
got 2
scala> mayBeThere match {
| case Some(x) => println("got " + x)
| }
<console>:13: warning: match may not be exhaustive.
It would fail on the following input: None
mayBeThere match {
^
error: No warnings can be incurred under -Xfatal-warnings.
scala> i
res98: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
scala> l
res99: List[Emp] = List(Emp(John,30), Emp(Jim,28), Emp(Jack,32))
scala> case class Emp(name:String, desig:String)
defined class Emp
scala> val list = Emp("John", "SE") :: Emp("Jim", "SE") :: Emp("Jack", "SSE") :: Emp("Jill", "SSE")::Nil
list: List[Emp] = List(Emp(John,SE), Emp(Jim,SE), Emp(Jack,SSE), Emp(Jill,SSE))
scala> list.group
groupBy grouped
scala> list.groupBy(x => x.desig)
res100: scala.collection.immutable.Map[String,List[Emp]] = Map(SSE -> List(Emp(Jack,SSE), Emp(Jill,SSE)), SE -> List(Emp(John,SE), Emp(Jim,SE)))
scala> list.groupBy(x => x.desig).mapValues(x => x.size)
res101: scala.collection.immutable.Map[String,Int] = Map(SSE -> 2, SE -> 2)
scala>
scala> val list = Emp("John", "SE") :: Emp("Jim", "SE") :: Emp("Jack", "SSE") :: Emp("Jill", "SSE")::Nil
list: List[Emp] = List(Emp(John,SE), Emp(Jim,SE), Emp(Jack,SSE), Emp(Jill,SSE))
scala> list.for
forall foreach formatted
scala> list.foreach(x => "name " + x.name))
<console>:1: error: ';' expected but ')' found.
list.foreach(x => "name " + x.name))
^
scala> list.foreach(x => println("name " + x.name))
name John
name Jim
name Jack
name Jill
scala> list
res103: List[Emp] = List(Emp(John,SE), Emp(Jim,SE), Emp(Jack,SSE), Emp(Jill,SSE))
scala> list.head
res104: Emp = Emp(John,SE)
scala> val el = List()
el: List[Nothing] = List()
// Prefer .headOption than .head
scala> el.head
java.util.NoSuchElementException: head of empty list
at scala.collection.immutable.Nil$.head(List.scala:428)
at scala.collection.immutable.Nil$.head(List.scala:425)
... 36 elided
scala> el.headOption
res106: Option[Nothing] = None
scala> list.headOption
res107: Option[Emp] = Some(Emp(John,SE))
scala> list.last
res108: Emp = Emp(Jill,SSE)
scala> list.lastOption
res109: Option[Emp] = Some(Emp(Jill,SSE))
scala> el.last
last lastIndexOf lastIndexOfSlice lastIndexWhere lastOption
scala> el.lastOption
res110: Option[Nothing] = None
scala> val age = 20
age: Int = 20
scala> val isAdult = if(age > 18) true else false
isAdult: Boolean = true
scala> age =16
<console>:12: error: reassignment to val
age =16
^
scala> age =16
<console>:12: error: reassignment to val
age =16
^
scala>
scala>
scala> l
res111: List[Emp] = List(Emp(John,30), Emp(Jim,28), Emp(Jack,32))
scala> def computeFullName(firstName:Option[String], middleName:Option[String], lastName:Option[String]):Option[String] = {
| for (
| fn <- firstName;
| ln <- lastName
| ) yield fn + middleName.getOrElse(" ") + ln
| }
computeFullName: (firstName: Option[String], middleName: Option[String], lastName: Option[String])Option[String]
scala> computeFullName(Some("John"), None, Some("Doe"))
res0: Option[String] = Some(John Doe)
scala> computeFullName(Some("John"), None, None)
res1: Option[String] = None
scala> computeFullName(None, None, Some("Doe"))
res2: Option[String] = None
scala> computeFullName(Some("John"), Some("Middle"), Some("Doe"))
res3: Option[String] = Some(JohnMiddleDoe)
scala>
[success] Total time: 857 s, completed 22 May, 2019 1:01:07 PM
[Foo] $ project Foodata
[info] Set current project to Foodata (in build file:/Users/sanjib/temp/foo/)
[Foodata] testOnly *FoodataTestSuite -- -n size
[info] Compiling 1 Scala source to /Users/sanjib/temp/foo/modules/foo/Foodata/target/scala-2.12/test-classes ...
[info] Done compiling.
No of employees = 1
[info] FoodataTestSuite:
[info] - no of emplyess
[info] ScalaTest
[info] Run completed in 1 second, 359 milliseconds.
[info] Total number of tests run: 1
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 1, failed 0, canceled 0, ignored 0, pending 0
[info] All tests passed.
[info] Passed: Total 1, Failed 0, Errors 0, Passed 1
[success] Total time: 5 s, completed 22 May, 2019 1:01:51 PM
[Foodata] testOnly *FoodataTestSuite -- -n size1
[info] Compiling 1 Scala source to /Users/sanjib/temp/foo/modules/foo/Foodata/target/scala-2.12/test-classes ...
[info] Done compiling.
[info] FoodataTestSuite:
[info] - no of emplyess
[info] ScalaTest
[info] Run completed in 980 milliseconds.
[info] Total number of tests run: 1
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 1, failed 0, canceled 0, ignored 0, pending 0
[info] All tests passed.
[info] Passed: Total 1, Failed 0, Errors 0, Passed 1
[success] Total time: 3 s, completed 22 May, 2019 1:05:22 PM
[Foodata] testOnly *FoodataTestSuite -- -n size1
[info] Compiling 1 Scala source to /Users/sanjib/temp/foo/modules/foo/Foodata/target/scala-2.12/test-classes ...
[info] Done compiling.
[info] FoodataTestSuite:
[info] - no of emplyess *** FAILED ***
[info] 1 did not equal 2 (FoodataTestSuite.scala:26)
[info] ScalaTest
[info] Run completed in 993 milliseconds.
[info] Total number of tests run: 1
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 0, failed 1, canceled 0, ignored 0, pending 0
[info] *** 1 TEST FAILED ***
[error] Failed: Total 1, Failed 1, Errors 0, Passed 0
[error] Failed tests:
[error] com.foodata.FoodataTestSuite
[error] (Test / testOnly) sbt.TestsFailedException: Tests unsuccessful
[error] Total time: 2 s, completed 22 May, 2019 1:05:28 PM
[Foodata]