Scala Tutorials
Scala Tutorials
res0: Int = 37
V
e
n
u
i
s
m
y
f
i
r
s
t
n
a
m
e
V
e
n
u
K
a
t
r
a
g
a
d
a
// foreach is iterate over every character in the string
text.foreach(println)
smalltext.drop(2)
//Take is a method to get only specified number of characters
res2: String = nu is software developer
smalltext.take(2)
//capitalize the data
res3: String = Ve
smalltext.capitalize
//convert as Upper case
smalltext.toUpperCase()
res5: String = VENU IS SOFTWARE DEVELOPER
//convert string as LowerCase
smalltext.toLowerCase()
res6: String = venu is software developer
name == name3.toLowerCase()
name2 == name1.capitalize
res8: Boolean = false
name2.toLowerCase() ==name
res9: Boolean = true
name.equalsIgnoreCase(name3)
//To get data in second line you have to use \n or \t use this type of escapsed
characters
val text2 = "Venu is my first name \n Venu\tKatragadd is my full name"
//If you want to insert exactly raw data use """ thriple quotes """
val s1 = """
|Line 1.
|Line 2.
|Line 3."""
s1: String =
|Line 1.
|Line 2.
|Line 3.
val s1 = """
|Line 1.
|Line 2.
|Line 3.""".stripMargin('|')
s1: String =
Line 1.
Line 2.
Line 3.
val s = """
|Line 1.
|Line 2.
|Line 3.""".stripMargin.replaceAll("\n", " ")
text.split(" ")
res0: Array[String] = Array(Venu, is, my, first, name, Venu, Katragadda)
Venu
is
my
first
name
Venu
Katragadda
res0: Unit = ()
//split based on ,
val s = "eggs, milk, butter, Coco Puffs"
//s: String = eggs, milk, butter, Coco Puffs
s.split(",").map(_.trim)
res0: Array[String] = Array(eggs, milk, butter, Coco Puffs)
//Here map is a function trim is a method
//Scala map is a collection of key/value pairs. Any value can be retrieved based on
its key. Keys are unique in the Map, but values need not be unique.
val age = 30
age: Int = 30
/**supported characters
%c Character
%d Decimal number (integer, base 10)
%e Exponential floating-point number
%f Floating-point number
%i Integer (base 10)
%o Octal number (base 8)
%s A string of characters
%u Unsigned decimal (integer) number
%x Hexadecimal number (base 16)
%% Print a �percent� character
\% Print a �percent� character
*/
///////////1.5. Processing a String One Character at a Time//////
f
r
i
e
n
d
/** println(c)
Here println is a statement it not return anything. it's not possible to process
again
so I want to capitalize those wards what should you do?
*/
//use yield
//map or for/yield approaches are used to transform one collection into another
scala> matches.foreach(println)
92471150
9997788
87899247
234
//Now you can make it in array format
//This is best example to get only phone numbers from twitter or raw data
//Second way to apply regex
import scala.util.matching.Regex
//////////Match ///////
val AP = """([^924]{3,})([0-9]{3,})([0-9]{4,10})""".r
val KA = "[9916][0-9]+".r
//supported datatypes
phone.replaceFirst("[0-9]", "x")
val ThisMonth:Int = 1
val month = ThisMonth match {
case 1 => "January"
case 2 => "February"
case 3 => "March"
case 4 => "April"
case 5 => "May"
case 6 => "June"
case 7 => "July"
case 8 => "August"
case 9 => "September"
case 10 => "October"
case 11 => "November"
case 12 => "December"
case _ => "Invalid month" // the default, catch-all
}
val i = 5
i match {
case 1 | 3 | 5 | 7 | 9 => println("odd")
case 2 | 4 | 6 | 8 | 10 => println("even")
}
scala> findtype("venu")
res50: String = venu is a String
scala> Short.MinValue
res0: Short = -32768
scala> Short.MaxValue
res1: Short = 32767
//Tip: Short. next press tab to get suggestions
scala> Int.MinValue
res2: Int = -2147483648
scala> Float.MinValue
res3: Float = -3.4028235E38
scala> 19.45.toInt
res0: Int = 19
scala> 19.toFloat
res1: Float = 19.0
scala> 19.toDouble
res2: Double = 19.0
scala> 19.toLong
res3: Long = 19
scala> a.isValidByte
res0: Boolean = false
scala> a.isValidShort
res1: Boolean = true
scala> val a = 1
a: Int = 1
scala> val a = 1d
a: Double = 1.0
scala> val a = 1f
a: Float = 1.0
scala> var a = 1
a: Int = 1
scala> a += 1
scala> println(a)
2
scala> a -= 1
scala> println(a)
1
scala> var i = 1
i: Int = 1
scala> i *= 2
scala> println(i)
2
scala> i *= 2
scala> println(i)
4
scala> i /= 2
scala> println(i)
2
................
scala> var x = 1d
x: Double = 1.0
scala> x += 1
scala> println(x)
2.0
scala> var x = 1f
x: Float = 1.0
scala> x += 1
scala> println(x)
2.0
////////////////////2.6. Handling Very Large Numbers/////
scala> var b = BigInt(1234567890)
b: scala.math.BigInt = 1234567890
scala> b + b
res0: scala.math.BigInt = 2469135780
scala> b * b
res1: scala.math.BigInt = 1524157875019052100
scala> b += 1
scala> println(b)
1234567891
scala> b.toInt
res2: Int = 1234567891
scala> b.toLong
res3: Long = 1234567891
scala> b.toFloat
res4: Float = 1.23456794E9
scala> b.toDouble
res5: Double = 1.234567891E9
scala> BigInt.MaxLong
warning: there were 1 deprecation warning(s); re-run with -deprecation for details
res38: scala.math.BigInt = 9223372036854775807
// random characters
scala> r.nextPrintableChar
res0: Char = H
scala> r.nextPrintableChar
res1: Char = r
scala> val r = 1 to 10
r: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5,
6, 7, 8, 9, 10)
scala> val r = 1 to 10 by 2
r: scala.collection.immutable.Range = Range(1, 3, 5, 7, 9)
//When creating a Range, you can also use until instead of to:
scala> for (i <- 1 until 5) println(i)
1
2
3
4
zipWithIndex
scala> a.foreach(println)
app
banana
orange
for {
i <- 1 to 10
if i != 1
if i % 2 == 0
} println(i)
2*1=2
2*2=4
2*3=6
2*4=8
2*5=10
2*6=12
2*7=14
2*8=16
2*9=18
2*10=20
//map function does the same thing: process and genrate new collection
scala> val out = fruits.map(_.toUpperCase)
val x = Array(99,999,333)
val x1 = Array(100,1000,334)
//////// If else///////
....sample functions......
def abs(x: Int, y:Int) = if (x >= 0) x else -x
def max(a: Int, b: Int) = if (a > b) a else b
val c = if (a > b) a else b
/////Functions///////
val name = "venu reddy"
name match {
case name if(name.contains("choudary")) => println("he is choudary")
case name if(name.contains("reddy")) => println("he is redddy")
case name if(name.contains("naidu")) => println("he is naidu from andhra")
case _ => println("he is not from Andhra")
}
scala> findtype("venu")
res50: String = venu is a String
//What is difference between function and method?
scala> val x =List.range(10,20)
x: List[Int] = List(10, 11, 12, 13, 14, 15, 16, 17, 18, 19)
//Define a Method
scala> def m1(i:Int)=i+2
scala> (i:Int)=>i+2
res0: Int => Int = <function1>
scala> x.map((x)=>x+2)
res2: List[Int] = List(12, 13, 14, 15, 16, 17, 18, 19, 20, 21)
//Method Accepting Argument
scala> m1(2)
res3: Int = 4
//Defining Function with val
scala> p(2)
res4: Int = 4
scala> p
res5: Int => Int = <function1>
Method is a part of class/object which denotes do something action. let eg: dog is
barking, here barking is method.
Function is a set of code, represented as an Object. It define a functionality
http://stackoverflow.com/questions/2529184/difference-between-method-and-function-
in-scala
scala> power(2, 8)
res6: Long = 256
nested functions
//////////////methods//////////
scala> val s = "vacation.jpg"
s: String = vacation.jpg
scala> d.round
res13: Long = 66
scala> d.floor
res14: Double = 65.0
scala> d.compare(18.0)
res15: Int = 1
scala> d.+(2.721)
/////////////////////////classes///////
scala> p.getName
Venu Katragadda
//p.getName works because it can access the name field.
*********Case classes***********
almost similar to class, but no need to define val or var
Case classes are used to conveniently store and match on the contents of a class.
You can construct them without using new.
http://www.alessandrolacava.com/blog/scala-case-classes-in-depth/
Lists:
Lists came from java class called ArrayLists. So it's immutable. It's also similar
to Array, but Immutable
Lists preserve order, can contain duplicates, and are immutable. If you try to
update, reassign another value getting error
scala> 1 to 9 toList
warning: there were 1 feature warning(s); re-run with -feature for details
res56: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
scala> (1 to 9).toList
res57: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
scala> 1 to 19 by 2 toList
warning: there were 1 feature warning(s); re-run with -feature for details
res58: List[Int] = List(1, 3, 5, 7, 9, 11, 13, 15, 17, 19)
Sets
Sets do not preserve order and have no duplicates. Sets also immutable
Touple:
A tuple groups together simple logical collections of items without using a class.
scala> val hostPort = ("localhost", 80)
hostPort: (String, Int) = (localhost, 80)
Unlike case classes, they don�t have named accessors, instead they have accessors
that are named by their position and is 1-based rather than 0-based.
scala> hostPort._1
res0: String = localhost
scala> hostPort._2
res1: Int = 80
Another way to create touple.
val mobile = "Venu" -> 987678
mobile: (String, Int) = ("Venu",987678)
mobile._1
mobile._2