Java and
Scala needs to be installed in VM
Using
phython – streaming and machine learning having some issues
Scala is
little bit tough
Installation
of scala
Java -> sudo apt-get install openjdk-8-jdk
Java -> sudo apt-get install openjdk-7-jdk(Optional)
Scala -> www.scala-lang.org -> Download the latest One.
Go to Downloads -> tar -xvzf scala-file
sudo mv scala-2.11.7 /usr/local/scala
sudo nano .bashrc
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
export SCALA_HOME=/usr/local/scala
export PATH=$PATH:$SCALA_HOME/bin
source ~/.bashrc
if you
want to practice in windows
you can
do like below
click
download
scala-2.11.7
once
this done
you can
go to cmd promt
go to
bin
type
scala
you can
get the REPL
java 1.8
and scala is similar ?
no this
not similar some features they introudec that’s it
java 8 –
is not funcational programming language
Scala –
fully matured
Type
inferences
Virtual
extensive
Fully
functional
Immutability
Conventional
imperative language
Lamda
collections – higher order functions (reuse and self-explanatory)
SCALA:
Slogan writes less do more
Immutability
: you cant change at anytime
Scala is
very faster than java
Java
imitates scala play bean field
Some history
:
1996:
java 1.0 1980’s –
LISP& Machine learning
1997:
PIZZA 1999 --
HASKELL
1998: GJ 2001 -- Funnel
2000:
java 1.3
2004:
java 1.4
Incorporate
both PIZZA came
2006 –
they included all
Why
scala in demand – its has Interactive Shell
Java
don’t have the interactive shell
Evech
and every line we cant debug and run in java
SCALA
provides Interactive Shell
REPL Stands
Read
Evaluate
Print
Loop
Read –
compiles – results – loop
Most of
the development will have in interactive shell
Variables:
Mutable
– change
Immutable -- constants
Scala
only immutable data types
Mutalable
– var
Immutable
– val
Type
inference – you no need to give this will let you know what its type
SCALA –
scalable language
Default
in scala is immutable
Def:
define the funtions
PLAY :
IDE for Spark – web based application by play
Expression,Variables,types,Functions
Variables
Functions
Expressions
Practice:
scala>
"this is my text "
res16:
String = "this is my text "
he re
just I given single quotes it will print the same val duing the data type
variables:
scala>
'a'
res31:
Char = a
scala>
1
res32:
Int = 1
scala>
2.3
res33:
Double = 2.3
scala>
2.5f
res34:
Float = 2.5
scala>
"Hello world"
res35:
String = Hello world
if you
want to see the all the commands which are using REPL you can type below
type :
scala> :
All
commands can be abbreviated, e.g., :he instead of :help.
:edit
<id>|<line> edit
history
:help
[command] print this summary or
command-specific help
:history
[num] show the history
(optional num is commands to show)
:h?
<string> search the
history
:imports
[name name ...] show import history, identifying sources of names
:implicits
[-v] show the implicits in scope
:javap
<path|class> disassemble a
file or class name
:line
<id>|<line> place
line(s) at the end of history
:load
<path> interpret lines
in a file
:paste
[-raw] [path] enter paste mode or
paste a file
:power enable power user mode
:quit exit the interpreter
:replay
[options] reset the repl and
replay all previous commands
:require
<path> add a jar to the
classpath
:reset [options] reset the repl to its initial state,
forgetting all session entries
:save
<path> save replayable
session to a file
:sh
<command line> run a shell
command (result is implicitly => List[String])
:settings
<options> update compiler
options, if possible; see reset
:silent disable/enable automatic
printing of results
:type
[-v] <expr> display the type
of an expression without evaluating it
:kind
[-v] <expr> display the kind
of expression's type
:warnings show the suppressed warnings
from the most recent line which had any
:line
:edit
:history
: reply
:t : type of expression
without evaluating
:t
“hellp”
This means “type of expression without
evaluating “
scala>
:t
:type
[-v] <expression>
:t
“dsdsd”
scala> :help t
display
the type of an express
scala>
:t 3
Int
scala>
:t 5+3
Int
scala>
:t 'e'
Char
scala>
:t "dsdsd"
String
scala>
:t "dsdsdsd"+"dsdsd"
String
scala>
if you
need any help related any command you can simply use the
:help t
like this
scala> print("Hello World")
Hello World
scala> print(2)
2
scala> print(2+3)
5
scala> val x = 2 + 3
x: Int = 5
scala> print(x)
5
You can
assing the value like
Val x =
30;
:t
x à you can find the type of the
expression
You can
give the type of val
Like
Val
k:String=”siddu”
K
Scala Clear
the screen: Ctrl + L
BigINT:
You can
declare as BigInt like below
scala> val
i=BigInt("8498398438949834983984839443434343434")
i:
scala.math.BigInt = 8498398438949834983984839443434343434
scala>
i+1
res1:
scala.math.BigInt = 8498398438949834983984839443434343435
BigDecimal:
scala>
val i=BigDecimal("1.8498398438949834983984839443434343434")
i:
scala.math.BigDecimal = 1.8498398438949834983984839443434343434
Defining methods:
Def add(x:Double)= x+y
You can
pass any value for these defined functions
Def
add(x:Int):Double=x+y*x-10
You can
mention the return type of the method as well
scala>
def f2c (x : Double) : Double = (x-32)*5/9.0
f2c: (x:
Double)Double
scala>
def f2c (x : Double) : Int = (x-32)*5/9.0
<console>:11:
error: type mismatch;
found
: Double
required: Int
def f2c (x : Double) : Int =
(x-32)*5/9.0
^
scala>
def squareThenAdd ( x:Int,y:Int) = x*x + y*y
squareThenAdd:
(x: Int, y: Int)Int
scala>
def squareThenAdd ( x:Int,y:Int) :Double = x*x + y*y
squareThenAdd:
(x: Int, y: Int)Double
scala>
squareThenAdd(5,4)
res29:
Double = 41.0
scala>
def squareThenAdd ( x:Int,y:Int) = x*x +
y*y
squareThenAdd:
(x: Int, y: Int)Int
scala>
squareThenAdd(5,4)
res30:
Int = 41
scala>
def squareThenAdd ( x:Int) = x*x + y*y
squareThenAdd:
(x: Int)Int
Tuples and lists
Tuples
and List are the data structures
You can
store multiple lines working with group of elements
Val
(int1, int2) = (2,4)
Val._1
Val._2
Val._3
Based on
this you can retrieve
Scala>
Val twoInts=(2,4)
scala>
val twonts =(3,4)
twonts:
(Int, Int) = (3,4)
scala>
val twoStrings=("siddu","how are you")
twoStrings:
(String, String) = (siddu,how are you)
scala>
val threeDoubles=(1.2,1.3,4.5)
threeDoubles:
(Double, Double, Double) = (1.2,1.3,4.5)
scala>
val intAndString= (4,"siddu")
intAndString:
(Int, String) = (4,siddu)
·
Tuples
you can do max 22 not more than that.
Create
List
Val
list=List(3,4,5,6)
You can
do all the list actions with in it
DROP:
You can
drop the elements with in List
scala>
val removeList=List(1,2,3,"naraismha","siddu")
removeList:
List[Any] = List(1, 2, 3, naraismha, siddu)
scala>
re
removeList res1
res10 res11 res12
res13 res3 res4
res5 res6 res7
res9 ref reflect
scala>
re
<console>:11:
error: not found: value re
re
^
scala>
removeList
res15:
List[Any] = List(1, 2, 3, naraismha, siddu)
scala>
val listAfterRemove=removeList.drop(2)
listAfterRemove:
List[Any] = List(3, naraismha, siddu)
scala>
listAfterRemove
res16:
List[Any] = List(3, naraismha, siddu)
List
examples more:
Defining
list:
scala> val fruits=List("apple","mango","bananna","grapes")
fruits: List[String] = List(apple, mango, bananna,
grapes)
scala> val digits=List(1,2,3,4,5,6,7)
digits: List[Int] = List(1, 2, 3, 4, 5, 6, 7)
scala> val empty=List()
empty: List[Nothing] = List()
scala> val mullists=List(
|
List(1,0,0),
|
List(0,1,0),
|
List(0,0,1)
| )
mullists: List[List[Int]] = List(List(1, 0, 0),
List(0, 1, 0), List(0, 0, 1))
List
can have return type as well like below example
scala>
val fruits:List[String]=List("apple","mango","bananna","grapes")
fruits:
List[String] = List(apple, mango, bananna, grapes)
scala>
val digits:List[Int]=List(1,2,3,4,5,6,7)
digits:
List[Int] = List(1, 2, 3, 4, 5, 6, 7)
scala>
val mullists:List[List[Int]]=List(
| List(1,0,0),
| List(0,1,0),
| List(0,0,1)
| )
mullists:
List[List[Int]] = List(List(1, 0, 0), List(0, 1, 0), List(0, 0, 1))
scala>
val empty:List[Nothing]=List()
empty:
List[Nothing] = List()
scala>
val empty:List[String]=List()
empty:
List[String] = List()
Note:
you can give either Nothing/String both can be accepts.
::
For using this you need to
specify as ( left paranthis at any point of time )
scala>
val
fruits="apple"::("orange"::("pottato"::("grapes"::Nil)))
fruits:
List[String] = List(apple, orange, pottato, grapes)
scala>
val nums=1::(2::(3::(4::(5::Nil))))
nums:
List[Int] = List(1, 2, 3, 4, 5)
For
numbers you can do like below
scala>
val numbers=1::2::3::4::Nil
numbers:
List[Int] = List(1, 2, 3, 4)
you
make a list like below one as well
scala>
val xs=List("a")
xs:
List[String] = List(a)
scala>
val ys=List("b")
ys:
List[String] = List(b)
scala>
val zs=List("c")
zs:
List[String] = List(c)
scala>
val list1=xs:::ys:::zs
list1:
List[String] = List(a, b, c)
scala>
val list2=xs:::(ys:::zs)
list2:
List[String] = List(a, b, c)
MKString:
scala>
test.mkString("2");
res17:
String = 122232425
here
this will add to after 0 index and return type as String
Contains:
scala>
test.contains(2)
res19:
Boolean = true
Length:
scala>
test.length
res20:
Int = 5
Count:
scala>
"hi how are you doing siddu".count(_=='a')
res0:
Int = 1
scala>
val myList=List(1,2,3,4,5,6,3,4,5,6,7)
myList:
List[Int] = List(1, 2, 3, 4, 5, 6, 3, 4, 5, 6, 7)
scala>
myList.count(_==4)
res1:
Int = 2
addString:
scala>
val str=new StringBuilder("hi")
str:
StringBuilder = hi
scala>
list.addString(str)
res27:
StringBuilder = hi123
scala>
list
res28:
List[Int] = List(1, 2, 3)
scala>
str
res29:
StringBuilder = hi123
Map:
scala>
val l = List(1,2,3,4)
l:
List[Int] = List(1, 2, 3, 4)
scala>
l.map(1+)
warning:
there was one feature warning; re-run with -feature for details
res37:
List[Int] = List(2, 3, 4, 5)
map
can add 1 by one in each element
scala>
l.map(1-)
warning:
there was one feature warning; re-run with -feature for details
res40:
List[Int] = List(0, -1, -2, -3)
if
you subtrack
it
will iterate as
1,2,3,4
– inside the list
1-1,
1-2,1-3,1-4
It
will add/subtrack like this
If
you want to import any package you have to do like below
scala>
import scala.math.
BigDecimal LowPriorityEquiv Pi atan expm1
min sin ulp
BigInt LowPriorityOrderingImplicits ScalaNumber atan2 floor
package sinh
E Numeric
ScalaNumericAnyConversions
cbrt hypot pow
sqrt
Equiv Ordered
ScalaNumericConversions
ceil log random
tan
Fractional Ordering abs cos log10
rint tanh
IEEEremainder PartialOrdering acos cosh log1p
round toDegrees
Integral PartiallyOrdered asin exp max
signum toRadians
scala>
import scala.math._
import
scala.math._
IF else condition
scala>
def serveBeer(custAge:Int)=if(custAge>=22) println("take KF beer")
else println("take water your not eligible")
serveBeer:
(custAge: Int)Unit
scala>
serveBeer(21)
take
water your not eligible
scala>
serveBeer(33)
take
KF beer
scala>
Write
a method and having some actions and action
Create
a list and apply that list into using map
All
the list values can be apply into particular function
scala>
val people=List(22,33,44,55)
people:
List[Int] = List(22, 33, 44, 55)
scala>
people.map
map mapConserve
scala>
people.map(serveBeer)
take
KF beer
take
KF beer
take
KF beer
take
KF beer
res3:
List[Unit] = List((), (), (), ())
scala>
here
the return type is List you want to convert as String simply you can use as
mkString like below
convert List type to string
scala>
list.map(ServBeer).mkString(" ")
res7:
String = please take water 11 please take KF beer please take KF beer please
take KF beer
scala>
list.map(ServBeer).mkString(" ,")
res8:
String = please take water 11 ,please take KF beer ,please take KF beer ,please
take KF beer
scala>
list.map(ServBeer).mkString(",")
res9:
String = please take water 11,please take KF beer,please take KF beer,please
take KF beer
Filter in List
If
you want to filter you can do like this but you can apply many things after
returned list
scala>
list.filter(20<)
warning:
there was one feature warning; re-run with -feature for details
res12:
List[Int] = List(22, 33, 44)
scala>
list.filter(20<).map(ServBeer)
warning:
there was one feature warning; re-run with -feature for details
res13:
List[String] = List(please take KF beer, please take KF beer, please take KF
beer)
scala>
list.filter(20<).map(ServBeer).mkString(" ")
warning:
there was one feature warning; re-run with -feature for details
res14:
String = please take KF beer please take KF beer please take KF beer
scala>
list.filter(20<).map(ServBeer).length
warning:
there was one feature warning; re-run with -feature for details
res16:
Int = 3
scala>
list.length
res17:
Int = 4
Retrieve the values from the list
scala>
list(0)
res20:
Int = 11
scala>
list(1)
res21:
Int = 22
scala>
list(2)
res22:
Int = 33
scala>
val
list:List[String]=List("cat","cow","elephent","deer")
list:
List[String] = List(cat, cow, elephent, deer)
scala>
list(0)
res31:
String = cat
scala>
def print(animal:String)=println(animal)
print:
(animal: String)Unit
scala>
list.map(print)
cat
cow
elephent
deer
res33:
List[Unit] = List((), (), (), ())
forEach in List
scala>
def mytest(passVal:Int)=println("hello this is int Val"+passVal)
mytest:
(passVal: Int)Unit
scala>
mytest(3)
hello
this is int Val3
scala>
customersList.for
forall foreach
scala>
customersList.foreach(mytest)
hello
this is int Val11
hello
this is int Val22
hello
this is int Val33
hello
this is int Val133
final defforeach(f: (A) ⇒ Unit): Unit
[use case]
Applies a function
f
to all
elements of this list.
Note: this method underlies the implementation of most other
bulk operations. Subclasses should re-implement this method if a more efficient
implementation exists.
f
the function that is applied for its side-effect to every
element. The result of function
f
is discarded.
Definition Classes
List → LinearSeqOptimized → IterableLike → GenericTraversableTemplate → TraversableLike → GenTraversableLike →TraversableOnce → GenTraversableOnce → FilterMonadic
Full Signature
final defforeach[U](f: (A) ⇒ U): Unit
scala>
list.foreach(a=> println(a.length +"hello this is list of each element
length"))
3hello
this is list of each element length
3hello
this is list of each element length
8hello
this is list of each element length
4hello
this is list of each element length
You
can pass the argument as well
For Loop in list
for
and yield
for
while iterates each iteration have the values that would be store
in buffer
in
this loop its create and buffer and store that value
each
type this going to save same type of the values for example
map
– can map the map values
list
having the list types..
examples
scala>
for (i <- 1 to 5) yield i
res10:
scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5)
scala>
for (i <- 1 to 10) yield i
res104:
scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5, 6, 7, 8, 9,
10)
scala> for (i<- 1 to 10) yield i*4
res115:
scala.collection.immutable.IndexedSeq[Int] = Vector(4, 8, 12, 16, 20, 24, 28,
32, 36, 40)
scala>
for(a <- list) println(a)
cat
cow
elephent
deer
scala>
:t for(a<-list)
scala>
:t for(a<-list) println(a)
Unit
scala>
val nums=List(1,2,3)
nums:
List[Int] = List(1, 2, 3)
scala>
nums.m
map mapConserve
max maxBy min
minBy mkString
scala>
nums.map(x=>x+1)
res117:
List[Int] = List(2, 3, 4)
scala>
nums.map(x=>x+1).map(x=>x*x)
res118:
List[Int] = List(4, 9, 16)
Zip
scala>
val names=List("narasimha","Anil", "hassan")
names:
List[String] = List(narasimha, Anil, hassan)
scala>
val
sunames=List("bodagala","vasidreedy","nandamuri")
sunames:
List[String] = List(bodagala, vasidreedy, nandamuri)
scala>
names.zip(sunames)
res125:
List[(String, String)] = List((narasimha,bodagala), (Anil,vasidreedy),
(hassan,nandamuri))
Adding two lists
scala>
names ++ sunames
res129:
List[String] = List(narasimha, Anil, hassan, bodagala, vasidreedy, nandamuri)
scala>
for((names,sunames) <- mixed) yield names + "\n"+ sunames
res133:
List[String] =
List(narasimha
bodagala,
Anil
vasidreedy,
hassan
nandamuri)
scala>
for((names,sunames) <- mixed) yield names + "/"+ sunames
res134:
List[String] = List(narasimha/bodagala, Anil/vasidreedy, hassan/nandamuri)
scala>
(for((names,sunames) <- mixed) yield names + "/"+
sunames).mkString("");
res135:
String = narasimha/bodagalaAnil/vasidreedyhassan/nandamuri
scala>
(for((names,sunames) <- mixed) yield names + " "+ sunames + "
").mkString("");
res145:
String = "narasimha bodagala Anil vasidreedy hassan nandamuri "
scala>
sentRaw.split(" ").toList.map(x=>x.split("/"))
res151:
List[Array[String]] = List(Array(The, DT), Array(index, NN), Array(of, IN),
Array(the, DT), Array(100, CD), Array(largest, JJS), Arra
rray(rose,
VBD), Array(modestly, RB), Array(as, IN), Array(well, RB), Array(., .))
cate
a mixed string and use some operations
scala>
sentRaw.split("
").toList.map(x=>x.split("/")).map(x=>Tuple2(x(0),x(1))
| )
res185:
List[(String, String)] = List((The,DT), (index,NN), (of,IN), (the,DT),
(100,CD), (largest,JJS), (Nasdaq,NNP), (financial,JJ), (stocks,NNS),
(rose,VBD), (modestly,RB), (as,IN), (well,RB), (.,.)
)
scala>
scala>
val (a,b)=listpairs.unzip
a:
List[String] = List(The, index, of, the, 100, largest, Nasdaq, financial,
stocks, rose, modestly, as, well, .)
b:
List[String] = List(DT, NN, IN, DT, CD, JJS, NNP, JJ, NNS, VBD, RB, IN, RB, .)
Regular Expressions:
Scala supports regular
expressions through Regex class available in the scala.util.matching
package
scala>
val ambm="a+b+"
ambm:
String = a+b+
scala>
val ambm="a+b+".r
ambm:
scala.util.matching.Regex
= a+b+
in
the above example you can observe one thing as .r (stands as regular
expression)
scala>
val worddigit1="\\w+\\dd+".r
worddigit1:
scala.util.matching.Regex = \w+\dd+
scala>
val WordDigit2 = """\\w+\\d+""".r
WordDigit2:
scala.util.matching.Regex = \\w+\\d+
scala>
val adder = "We're as similar as two dissimilar things in a
pod.\n\t-Blackadder"
adder:
String =
We're
as similar as two dissimilar things in a pod.
-Blackadder
scala>
adder.split("\\s|")
res7:
Array[String] = Array("", W, e, ', r, e, "", a, s,
"", s, i, m, i, l, a, r, "", a, s, "", t, w, o,
"", d, i, s, s, i, m, i, l, a, r, "", t, h, i, n, g, s,
"", i, n, "", a, "", p, o, d, ., "",
""
,
-, B, l, a, c, k, a, d, d, e, r)
scala>
adder.split("\\s+")
res8:
Array[String] = Array(We're, as, similar, as, two, dissimilar, things, in, a,
pod., -Blackadder)
split
with space
scala>
val Name = """(Mr|Mrs|Ms)\. ([A-Z][a-z]+)
([A-Z][a-z]+)""".r
Name:
scala.util.matching.Regex = (Mr|Mrs|Ms)\. ([A-Z][a-z]+) ([A-Z][a-z]+)
scala>
val Name(title,firstname,lastname) = "Mr. Narasimharao Bodagala"
title:
String = Mr
firstname:
String = Narasimharao
lastname:
String = Bodagala
Here
once the match happens this will display as the names
scala>
:t Name
scala.util.matching.Regex
Here
you observe the name of the value type is “scala.util.matching.Regex”
scala>
val Array(title,firsts,lasts) = "Mr. Narasimharao
Bodagala".split(" ")
title:
String = Mr.
firsts:
String = Narasimharao
lasts:
String = Bodagala
val
Name = """(Mr|Mrs|Ms)\. ([A-Z][a-z]+)
([A-Z][a-z]+)""".r
Name:
scala.util.matching.Regex = (Mr|Mrs|Ms)\. ([A-Z][a-z]+) ([A-Z][a-z]+)
scala>
Name. click as tab after dot)
anchored findAllIn findFirstIn findPrefixMatchOf isInstanceOf regex replaceFirstIn split
unanchored
asInstanceOf findAllMatchIn findFirstMatchIn findPrefixOf pattern replaceAllIn replaceSomeIn toString
unapplySeq
scala>
val smith="Mr. John Smith"
smith:
String = Mr. John Smith
scala>
val Name(title,fname,lname)=smith
title:
String = Mr
fname:
String = John
lname:
String = Smith
scala>
val matchesFound = Name.find
findAllIn findAllMatchIn findFirstIn
findFirstMatchIn
findPrefixMatchOf findPrefixOf
scala>
val matchesFound = Name.findAll
findAllIn findAllMatchIn
scala>
val matchesFound = Name.findAllIn(smith);
matchesFound:
scala.util.matching.Regex.MatchIterator = non-empty iterator
scala>
matchFound
res10:
scala.util.matching.Regex.MatchIterator = non-empty iterator
scala>
matchFound.fo
fold foldLeft
foldRight forall foreach
scala>
matchFound.foreach(print)
Mr.
Jhon Smith
scala>
val matchesFound = Name.findAllIn(smith).toList
matchesFound:
List[String] = List(Mr. John Smith)
scala>
matchesFound(0)
res2:
String = Mr. John Smith
scala>
val sentence = "Mr. John Smith said hello to Ms. Jane Hill and then to Mr.
Ramesh Rao";
sentence:
String = Mr. John Smith said hello to Ms. Jane Hill and then to Mr. Ramesh Rao
scala>
val matchList=Name.findAllIn(sentence)
matchList:
scala.util.matching.Regex.MatchIterator = non-empty iterator
scala>
val matchList=Name.findAllIn(sentence).toList
matchList:
List[String] = List(Mr. John Smith, Ms. Jane Hill, Mr. Ramesh Rao)
scala>
matchList(0)
res14:
String = Mr. John Smith
scala>
matchList(1)
res15:
String = Ms. Jane Hill
scala>
matchList(2)
res16:
String = Mr. Ramesh Rao
scala>
val matchList=Name.findAllIn(sentence).matchData
matchList:
Iterator[scala.util.matching.Regex.Match] = non-empty iterator
scala>
val matchList=Name.findAllIn(sentence).matchData.toList
matchList:
List[scala.util.matching.Regex.Match] = List(Mr. John Smith, Ms. Jane Hill, Mr.
Ramesh Rao)
scala>
val matchList=Name.findAllIn(sentence).matchData.toList.mkString("")
matchList:
String = Mr. John SmithMs. Jane HillMr. Ramesh Rao
scala>
val matchList=Name.findAllIn(sentence).matchData.toList.mkString(" ")
matchList:
String = Mr. John Smith Ms. Jane Hill Mr. Ramesh Rao
Map,Contains,getOrElse,WithDefault,Keys
and Values,groupBy,set,mapValues,keys and values,Option(Some and None),
scala> val engToDeu = Map(("dog","Hund"),("cat","katze"),("rhinoceros","Nashorn"))
engToDeu:
scala.collection.immutable.Map[String,String] = Map(dog -> Hund, cat ->
katze, rhinoceros -> Nashorn)
So
here dog – key
hund
is value
key
value pair as map
you
can retrieve the value based on the key like below
scala>
engToDeu("dog")
res20:
String = Hund
scala>
val engWord = List("dog","cat","rhinoceros");
engWord:
List[String] = List(dog, cat, rhinoceros)
scala>
val deuWords = List("Hund","katze","Nashorn")
deuWords:
List[String] = List(Hund, katze, Nashorn)
scala>
engWord.index
indexOf indexOfSlice indexWhere
scala>
engWord.indexOf("cat");
res15:
Int = 1
scala>
deuWords(engWord.indexOf("cat"));
res16:
String = katze
if
you want add any elemnts into the list along with key and value like below
scala>
engToDeu + "owl" -> "Eule";
res19:
(String, String) = (Map(dog -> Hund, cat -> katze, rhinoceros ->
Nashorn)owl,Eule)
Scala
Objects:
Its
like data + functions called as objects
Class
is nothing but blue print
Example:
object JohnSmith {
val firstName = "John"
val lastName = "Smith"
val age = 37
val occupation = "lingusist"
def fullName: String = firstName + " " + lastName
def greet(formal: Boolean): String = {
if(formal)
"Hello
my name is " +fullName+ "" + "and occupation: is" +occupation;
else
"Hello
my name is " +firstName + ""+ lastName
}
}
scala> JohnSmith.
age
asInstanceOf firstName fullName
greet isInstanceOf lastName
occupation toString
you can find all the values here
you can access anything inside the objects using any
data.
If you want to create another object you can do like the
below
object JhonDow {
val firstName = "John"
val lastName = "Dow"
val age = 24
val occupation = "Computerscitist"
def fullName: String = firstName + " " + lastName
def greet(formal: Boolean): String = {
if (formal)
"Hello
my name is " + fullName + "" + "and occupation: is" + occupation;
else
"Hello
my name is " + firstName + "" + lastName
}
}
You come to know the differences more here
You can call for different
scala> JohnDow.firstName
res15: String = John
scala> JohnDow.lastName
res16: String = Dow
scala> John
JohnDow JohnSmith
scala> JohnDow.fullName
res17: String = John
Dow
scala> JohnDow.greet(true)
res18: String = Hello my name is John Dowand occupation: isComputerscitist
so all seems same except few values in this case how you
can use here as
create two objects list and use
scala> val people=List(JohnDow,JohnSmith)
people: List[Object] = List(JohnDow$@598ec9af,
JohnSmith$@722a20ec)
scala> people.map(person=>person.firstName)
<console>:14: error: value firstName is not a
member of Object
people.map(person=>person.firstName)
^
Here getting error because of this you have to create a
class then create objects to call this.
Let me define the class now.
class person(
val firstName: String,
val lastName: String,
val age: Int,
val occupation: String) {
def fullName: String = firstName + " " + lastName
def greet(formal: Boolean): String = {
if (formal)
"Hello
my name is " + fullName + "" + "and occupation: is" + occupation;
else
"Hello
my name is " + firstName + "" + lastName
}
}
Once create the class you can see the magic
scala> val John
JohnDow JohnSmith
scala> val j1 = new person("John","Smith",35,"lingusit")
j1: person = person@4ce10d40
scala> val j2 = new
person("john","Dow",38,"scitist")
j2: person = person@190af581
scala> j1.
age
asInstanceOf firstName fullName
greet isInstanceOf lastName
occupation toString
scala> j1.firstName
res24: String = John
so how easy you can create dynamics things instead of
creating every time objects now you can create the list of elements of classes
like persons
scala> val people=List(j1,j2,j3,j4)
people: List[person] = List(person@4ce10d40,
person@190af581, person@2093decc, person@6c6cef3a)
see here
if you want to retrieve the values you can do the below
like
scala> people.map(t=>t.firstName)
res34: List[String] = List(John, john, john, john)
scala> people.map(t=>t.age)
res37: List[Int] = List(35, 38, 48, 48)
scala> people.map(t=>t.age).sum
res38: Intscala>
people.map(t=>t.age).sum/people.length
res42: Int = 42 = 169
scala>
people.map(t=>t.age).sum/people.length.toDouble
res45: Double = 42.25
here list have different different objects
you can apply all the list operations for this .
scala> people.groupBy(t=>t.firstName)
res47:
scala.collection.immutable.Map[String,List[person]] = Map(john ->
List(person@190af581, person@2093decc, person@6c6cef3a), John -> List(
scala>
people.groupBy(t=>t.firstName)("john").foreach(j=>println(j.greet(true)))
Hello my name is john
Dowand occupation: isscitist
Hello my name is john
pppmewand occupation: isdramist
Hello my name is john
mewand occupation: isdramist
Trait:
Its similar like interface in java
They renames as trait in scala that’s it
You can write a definations only nothing more than this
required
scala> trait worker {
|
| def workGreeting : String
| }
Defined trait worker
scala> class Student(School:String,Subject:String)
extends worker{
|
| def workGreeting="I am Studying
@"+ Subject + " @ " +
School;
|
| }
defined class Student
scala> val ts = new
Student("ZPHS","Telugu")
ts: Student = Student@28bedd32
scala> ts.workGreeting
res61: String = I am Studying @Telugu @ ZPHS
scala> ts.School
<console>:14: error: value School is not a member
of Student
ts.School
^
Why here we cant access the School/subject so
Apply Functionality
scala> object addone {
| def
m1(x:Int)=x+2 }
defined object addone
scala> addone.m1(5)
res63: Int = 7
you can apply without calling of this
scala> object addone {
| def
apply(x:Int)=x+6 }
defined object addone
scala> addone(3)
res68: Int = 9