Anda di halaman 1dari 22

val text = "Venu is my first name Venu Katragadda"

text: String = Venu is my first name Venu Katragadda

val smalltext = "Venu is software developer"


smalltext: String = Venu is software developer

//length of the string


text.length()

res0: Int = 37

//concat two strings using + method


val full_text = smalltext + text

full_text: String = Venu is software developerVenu is my first name Venu Katragadda

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)

//Tip: use text. next enter tab to get supported methods


//Filter the character using filter method

val result = smalltext.filter(_ != 'e')

result: String = Vnu is softwar dvlopr

//read from console


val names = readLine("Please enter your name:")

Please enter your name:names: String = null

//drop is a method to drop first number of characters.

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

res4: String = Venu is software developer

smalltext.toUpperCase()
res5: String = VENU IS SOFTWARE DEVELOPER
//convert string as LowerCase
smalltext.toLowerCase()
res6: String = venu is software developer

//You can apply different metods at a time.


smalltext.drop(12).take(12).capitalize

///////////1.1. Testing String Equality/////////


var name = "venu katragadda"
name: String = venu katragadda
var name1 = "venu"+"katragadda"
name1: String = venukatragadda
var name2 = "Venu Katragadda"
name2: String = Venu Katragadda
var name3 = "VENU KATRAGADDA"
name3: String = VENU KATRAGADDA
//Test two strings use == quotes, but if you use = its assignment
var equal_or_not = name == name1
equal_or_not: Boolean = false

name == name3.toLowerCase()

res7: Boolean = true

name2 == name1.capitalize
res8: Boolean = false

name2.toLowerCase() ==name
res9: Boolean = true
name.equalsIgnoreCase(name3)

res10: Boolean = true

////////////1.2 Creating Multiline Strings/////////


val text1 = "Venu is my first name" +
" Venu Katragadd is my full name"
text1: String = Venu is my first name Venu Katragadd is my full name

//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"

text2: String = Venu is my first name


Venu Katragadd is my full name

//If you want to insert exactly raw data use """ thriple quotes """

val text3 = "Venu is my first name \n Venu\tKatragadd is my full name"


text3: String = Venu is my first name
Venu Katragadd is my full name
val text4 = """Venu is my first name \n Venu\tKatragadd" +
"came from Hyderabad"
"30 year's of age"
"number one"""
text4: String = Venu is my first name \n Venu\tKatragadd" +
"came from Hyderabad"
"30 year's of age"
"number one

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", " ")

s: String = Line 1. Line 2. Line 3.

//where stripMargin split based on condition and replace based on stripmargin


output
More: http://www.dotnetperls.com/strip-scala

///////1.3. Splitting Strings///


//Split based on condition
val text = "Venu is my first name Venu Katragadda"
text: String = Venu is my first name Venu Katragadda

text.split(" ")
res0: Array[String] = Array(Venu, is, my, first, name, Venu, Katragadda)

val result = text.split(" ").foreach(println)

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: String = eggs, milk, butter, Coco Puffs


s.split(",")
//res0: Array[String] = Array(eggs, milk, butter, Coco Puffs)

res0: Array[String] = Array(eggs, milk, butter, Coco Puffs)


//strip white spaces using trim method

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.

////////////1.4. Substituting Variables into Strings//////////


//string interpolation in Scala

val name = readLine("Please enter your name:");

name: String = venu

val age = 30
age: Int = 30

//3 ways interpolation


////first process
println(s"$name is $age years old, after 2 years my age : ${age+2}")
venu is 30 years old, after 2 years my age : 32

println(s"You are 33 years old: ${age == 33}")


You are 33 years old: false
res1: Unit = ()
//Please note here s is a method in print(s"")
//Plese note you can use raw also to execute like """ thriple cotes"""

val details = raw"Hi my self Venu \n katragadda here \t is not applied"


details: String = Hi my self Venu \n katragadda here \t is not applied
val weight = 70;
val paid = f"Hi $name weight is $weight%.0f Kgs."
paid: String = Hi venu weight is 70 Kgs.
//f is like printf in java

///////second process to interpolate string


val s = "%s is %d years old and his weight %d".

/**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//////

scala> val data = "Hi this is venu, my first program it is."


data: String = Hi this is venu, my first program it is.

scala> val upper = data.map(c => c.toUpper)


upper: String = HI THIS IS VENU, MY FIRST PROGRAM IT IS.
//Map is a function, that apply a logic on each character

scala> val upper = data.map(_.toUpper)


upper: String = HI THIS IS VENU, MY FIRST PROGRAM IT IS.

//you can apply different logics/methods at a time


val upper = data.filter(_ != 'i').map(_.toUpper)
upper: String = H THS S VENU, MY FRST PROGRAM T S.
//Here i is a character it filter i characters that output processed by map
function

scala> for (c <- "Hello friend") println(c)


H
e
l
l
o

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> val upper = for (c <- data) yield c.toUpper


upper: String = HI THIS IS VENU, MY FIRST PROGRAM IT IS.

val result = for {


c <- data
if c != 'i'
} yield c.toUpper

result: String = H THS S VENU, MY FRST PROGRAM T S.

//foreach method is typically used to operate on each element without returning a


result.

///////////////1.6. Finding Patterns in Strings

val numPattern = "[0-9]+".r


//here .r is a method that apply regix

//Find the numbers in the string


val phone = """Venu 92471150
satya 9997788
anuradha 87899247
but i don't use 234"""

val match1 = numPattern.findFirstIn(phone)


//display first occurance

scala> val matches = numPattern.findAllIn(phone)


matches: scala.util.matching.Regex.MatchIterator = non-empty iterator
//If you get list of items simply use foreach println

scala> matches.foreach(println)
92471150
9997788
87899247
234
//Now you can make it in array format

scala> val matches = numPattern.findAllIn(phone).toArray


matches: Array[String] = Array(92471150, 9997788, 87899247,234)

//task how to get only phone numbers from other numbers?


val numPattern = "[9][0-9]+".r

scala> val matches = numPattern.findAllIn(phone).toArray


matches: Array[String] = Array(92471150, 9997788, 99247)

//This is best example to get only phone numbers from twitter or raw data
//Second way to apply regex

import scala.util.matching.Regex

scala> val numPattern = new Regex("[7-9][0-9]{10}+")


numPattern: scala.util.matching.Regex = [7-9][0-9]+

scala> val matches = numPattern.findAllIn(phone).toArray


matches: Array[String] = Array(92471150, 9997788, 87899247)

scala> val match1 = numPattern.findFirstIn(phone)


match1: Option[String] = Some(92471150)

val result = numPattern.findFirstIn(phone).getOrElse("no match")

//////////Match ///////

val AP = """([^924]{3,})([0-9]{3,})([0-9]{4,10})""".r
val KA = "[9916][0-9]+".r

// more info http://www.w3schools.com/jsref/jsref_obj_regexp.asp


//http://www.mpi.nl/corpus/html/trova/ch01s04.html

//val mobile = Console.readInt()


val mobile = "9247159150"
val AP = "(^[7-9]{4}+)([0-9]{6}+)".r

val State_numbers = mobile match {


case AP => "Its Andhra number"
case KA => "Its Karnataka number"
case _ => "Its other state number"
}

val name = readLine("Please enter your name:")

val tasks = name match {


case "venu" => "Do redshift tasks today"
case "Jyothi" => "Do testing tasks today"
case "Goutami" => "Debug these commands today"
case "Koti" => "wait few days to job change"
case _ => "don't do anything simply take rest"
}

//supported datatypes

def supportsDataType(dataType: DataType): Boolean = dataType match {


case _: BinaryType => false
// We are using random data generator and the generated strings are not really
valid string.
case _: StringType => false
case _: BooleanType => false // see
https://issues.apache.org/jira/browse/SPARK-10442
case _: CalendarIntervalType => false
case _: DateType => false
case _: TimestampType => false
case _: ArrayType => false
case _: MapType => false
case _: StructType => false
case _: UserDefinedType[_] => false
case _ => true
}
//////////1.7. Replacing Patterns in Strings///

var phone = """Venu 92471150


satya 999-778-9908
anuradha 87899247
my sex is male"""

//Here i want to replace sex related data


phone.replaceAll("sex", "***")

I want to replace mobile numbers only


val pattern = """([0-9]{1,3})[ -]([0-9]{1,3})[ -]([0-9]{4,10})""".r

val block_numbers = pattern.replaceAllIn(phone, "x")

phone.replaceFirst("[0-9]", "x")

//let example change last name


scala> val data = "Jyothi katragadda"
data: String = venu katragadda
scala> val regex = "katragadda".r
regex: scala.util.matching.Regex = katragadda
//case sensitive it is
scala> val result = regex.replaceFirstIn(data, "patti")
result: String = Jyothi patti

///////1.8. Extracting Parts of a String That Match Patterns//


For example
val pattern = "([0-9]+)-([A-Za-z]+)".r
val pattern(count, fruit) = "100 Bananas"

//find movies name from un structured data


"movies near 80301"
"movies 80301"
"80301 movies"
"movie: 80301"
"movies: 80301"
"movies near boulder, co"
"movies near boulder, colorado"

// match "movies 80301"


val MoviesZipRE = "movies (\\d{5})".r

// match "movies near boulder, co"


val MoviesNearCityStateRE = "movies near ([a-z]+), ([a-z]{2})".r

//val findmovie = "please enter your 5 digits zip: "


val findmovie = "Movies 876543"
findmovie match {
case MoviesZipRE(zip) => "HI Movies in $zip are:"
case MoviesNearCityStateRE(city, state) => " movies in $city, $state :"
case _ => println("did not match a regex")
}

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")
}

val cmd = "stop"


cmd match {
case "start" | "go" => println("starting")
case "stop" | "quit" | "exit" => println("stopping")
case _ => println("doing nothing")
}

scala> def findtype(x: Any): String = x match {


| case s: String => s + " is a String"
| case i: Int => i+"is an Inteeger"
| case f: Float => f+ "is a Float number"
| case l: List[_] => l+ " is a List"
| case p: Array[_] => p+" is a Array"
| case _ => "Unknown"
| }
findtype: (x: Any)String

scala> findtype("venu")
res50: String = venu is a String

/////1.9. Accessing a Character in a String////


val data = "venu katragadda"
val x = data.charAt(0)
x(0)
x(6)

////////////////////2 Inteegers ./////////////


//Scala datatypes
Char 16-bit unsigned Unicode character ... 'a'
Byte 8-bit signed value
Short 16-bit signed value
Int 32-bit signed value
Long 64-bit signed value
Float 32-bit IEEE 754 single precision float
Double 64-bit IEEE 754 single precision float

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

////2.1. Parsing a Number from a String/////


scala> "100".toInt
res0: Int = 100
scala> "100".toDouble
res1: Double = 100.0
scala> "100".toFloat
res2: Float = 100.0
scala> "1".toLong
res3: Long = 1
scala> "1".toShort
res4: Short = 1
scala> "1".toByte
res5: Byte = 1

but to string to int is not possible


scala> "Venu".toInt
java.lang.NumberFormatException: For input string: "foo"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java)
at java.lang.Integer.parseInt(Integer.java:449)
... more output here ...

scala> val b = BigInt("1")


b: scala.math.BigInt = 1

scala> implicit class StringToInt(s: String) {


def toInt(radix: Int) = Integer.parseInt(s, radix)
}
defined class StringToInt
scala> "1".toInt(2)
res0: Int = 1
scala> "10".toInt(2)
res1: Int = 2
scala> "100".toInt(2)
res2: Int = 4
scala> "100".toInt(8)
res3: Int = 64
scala> "100".toInt(16)
res4: Int = 256
/////////////2.2. Converting Between Numeric Types (Casting)/////
val a = 1945

scala> val b = a.to[Tab]


toByte toChar toDouble toFloat toInt toLong
toShort toString

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> val b = a.toFloat


b: Float = 1945.0

scala> a.isValidByte
res0: Boolean = false

scala> a.isValidShort
res1: Boolean = true

///////////2.3. Overriding the Default Numeric Type//////

scala> val a = 1
a: Int = 1

scala> val a = 1d
a: Double = 1.0

scala> val a = 1f
a: Float = 1.0

scala> val a = 1000L


a: Long = 1000
.................................
scala> val a = 99: Byte
a: Byte = 99
scala> val a:Int = 99

/////////////2.4. Replacements for ++ and --///////


++ and -- are replaced with the += and -= methods:
scala> val x = 1
x: Int = 1
scala> x += 1
<console>:9: error: value += is not a member of Int

// -- or ++ applicable for var only not val


//Please note: the symbols +=, -=, *=, and /= aren�t operators, they�re
methods.

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

//////////2.7. Generating Random Numbers //////


scala> val r = scala.util.Random
r: scala.util.Random = scala.util.Random@13eb41e5
scala> r.nextInt
res0: Int = -1323477914

//Int from 0 to 99.


scala> r.nextInt(100)
res1: Int = 58
// returns a value between 0.0 and 1.0
scala> r.nextFloat
res2: Float = 0.50317204
You can create random Double values:
// returns a value between 0.0 and 1.0
scala> r.nextDouble
res3: Double = 0.6946000981900997
scala> val r = new scala.util.Random(100)

// random characters
scala> r.nextPrintableChar
res0: Char = H
scala> r.nextPrintableChar
res1: Char = r

// create a random length range


scala> var range = 0 to r.nextInt(10)
range: scala.collection.immutable.Range.Inclusive = Range(0, 1, 2, 3)

scala> range = 0 to r.nextInt(10)


range: scala.collection.immutable.Range.Inclusive = Range(0, 1)

scala> for (i <- 0 to r.nextInt(10)) yield i * 2


res0: scala.collection.immutable.IndexedSeq[Int] = Vector(0, 2, 4)

scala> for (i <- 0 to r.nextInt(10)) yield r.nextPrintableChar


res2: scala.collection.immutable.IndexedSeq[Char] = Vector(x, K, ^, z, w)

scala> for (i <- 1 to 5) yield r.nextInt(100)

res3: scala.collection.immutable.IndexedSeq[Int] = Vector(88, 94, 58, 96, 82)

////2.8. Creating a Range, List, or Array of Numbers/////

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)

scala> for (i <- 1 to 5) println(i)


1
2
3
4
5

//When creating a Range, you can also use until instead of to:
scala> for (i <- 1 until 5) println(i)
1
2
3
4

scala> val x = 1 to 10 toArray


x: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
scala> val x = (1 to 10).toArray
x: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> val x = 1 to 10 toList


x: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
scala> val x = (1 to 10).toList
x: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> var range = 0 to scala.util.Random.nextInt(10)


range: scala.collection.immutable.Range.Inclusive = Range(0, 1, 2, 3)

scala> for (i <- 1 to 5) yield i * 2


res0: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10)

//////////////////////////3 Control Structures////

////3.1. Looping with for and foreach////////


scala> val nieces = List("emily", "hannah", "mercedes", "porsche")
nieces: List[String] = List(emily, hannah, mercedes, porsche)

scala> for (n <- nieces) yield n.capitalize


res0: List[String] = List(Emily, Hannah, Mercedes, Porsche)

val a = Array("app", "banana", "orange")

for(x <- a) println(x)

// you can apply conditions in for loop

scala> val a = Array("app", "banana", "orange")


a: Array[String] = Array(app, banana, orange)

scala> for (x <- a if x.length > 3) println(x)


banana
orange

//apply transformations/operations in for loop


scala> for (e <- a) {
val s = e.toUpperCase
println(s)
}
APP
BANANA
ORANGE

val newArray = for (e <- a) yield {


| // imagine this requires multiple lines
| val s = e.toUpperCase
| s
| }
newArray: Array[java.lang.String] = Array(APPLE, BANANA, ORANGE)
//**** yield return something (expression) but println is a statement don't return
anything *//

for (i <- 0 until a.length) {


println(s"$i is ${a(i)}")
}
That loops yields this output:
0 is app
1 is banana
2 is orange

zipWithIndex

zipWithIndex method that you can use to create a loop counter:


scala> for ((e, count) <- a.zipWithIndex) {
| println(s"$count is $e")
| }
0 is app
1 is banana
2 is orange

scala> for (i <- 1 to 10 if i < 4) println(i)


1
2
3

scala> a.foreach(println)
app
banana
orange

scala> a.foreach(e => println(e.toUpperCase))


APP
BANANA
ORANGE

scala> a.foreach { e =>


val s = e.toUpperCase
println(s)
}
APP
BANANA
ORANGE
for {
i <- 1 to 10
if i % 2 == 0
} println(i)

for {
i <- 1 to 10
if i != 1
if i % 2 == 0
} println(i)

scala> for (i <- 1 to 2; j <- 1 to 2) println(s"i = $i, j = $j")


i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2

scala> for (i <- 2 to 3; j <- 1 to 10) println(s"$i*$j="+i*j)

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

/////yield used to generate collection of lists


scala> val names = Array("venu", "madhav", "ramya")
names: Array[String] = Array(chris, ed, maurice)

Now capNames is new collection of list and ignore old lsit


scala> val capNames = for (e <- names) yield e.capitalize
capNames: Array[String] = Array(Chris, Ed, Maurice)

scala> val lengths = for (e <- names) yield {


// imagine that this required multiple lines of code
e.length
}
lengths: Array[Int] = Array(5, 2, 7)

//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///////

val absValue = if (4%2==0) println("even") else println("odd")


val absValue = if (4%2==0) "even" else "odd"

....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")
}

define same using function


............................
def testing(name: String) =
name match {

case name if(name.contains("reddy")) => println("he is redddy")


case name if(name.contains("choudary")) => println("he is choudary")
case name if(name.contains("naidu")) => println("he is naidu from andhra")
case _ => println("he is not from Andhra")
}

def findtype(x: Any): String = x match {


case s: String => s + " is a String"
case i: Int => i+"is an Inteeger"
case f: Float => f+ "is a Float number"
case l: List[_] => l+ " is a List"
case p: Array[_] => p+" is a Array"
case _ => "Unknown"
}
findtype("venu")

scala> def findtype(x: Any): String = x match {


| case s: String => s + " is a String"
| case i: Int => i+"is an Inteeger"
| case f: Float => f+ "is a Float number"
| case l: List[_] => l+ " is a List"
| case p: Array[_] => p+" is a Array"
| case _ => "Unknown"
| }
findtype: (x: Any)String

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

m1: (i: Int)Int


//Define a Function

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> val p =(i:Int)=>i+2


p: Int => Int = <function1>
//Argument to function is Optional

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

def fact(n: Int): Int = n match {


case 0 => 1
case n => n * fact( n-1)
}
def fib(n: Int): Int = n match {
case 0 => 1
case 1 => 1
case n => fib(n-1) + fib(n-2)
}
}

scala> def power(x: Int, n: Int): Long = {


if (n >= 1) x * power(x, n-1)
else 1
}
power: (x: Int, n: Int)Long

scala> power(2, 8)
res6: Long = 256
nested functions

scala> def max(a: Int, b: Int, c: Int) = {


| def max(x: Int, y: Int) = if (x > y) x else y
| max(a, max(b, c))
| }
max: (a: Int, b: Int, c: Int)Int

scala> max(42, 181, 19)


res10: Int = 181

scala> def sum(items: Int*): Int = {


| var total = 0
| for (i <- items) total += i
| total
| }
sum: (items: Int*)Int

scala> sum(10, 20, 30)


res11: Int = 60

//////////////methods//////////
scala> val s = "vacation.jpg"
s: String = vacation.jpg

scala> val isJPEG = s.endsWith(".jpg")


isJPEG: Boolean = true

scala> val d = 65.642


d: Double = 65.642

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///////

class Person(var name: String)


defined class Person

scala> val p = new Person("venu katragadda")


p: Person = Person@369e58be
// display name
scala> p.name
res0: String = venu katragadda

// updating name value ... var support


scala> p.name = "Goutami"
p.name: String = Goutami
scala> p.name
res1: String = Goutami

//if you try val you will get error

//update Fields without val or var also get error


//scala> class Person(name: String) also

//Adding private to val or var

scala> class Person(private var name: String) { def getName {println(name)} }


defined class Person
scala> val p = new Person("venu katragadda")
p: Person = Person@3cb7cee4
scala> p.name
<console>:10: error: variable name in class Person cannot be accessed in Person
p.name

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.

case class Person(name: String, age:Int, city: String)


Person.name
Person.age
Person.city

//Mostly used in spark


case class Person(firstName: String, lastName: String)

val me = Person("venu", "katragadda")


val first = me.firstName
val last = me.lastName

if (me == Person(first, last)) {


println("Found myself!")
println(me)
}

http://www.alessandrolacava.com/blog/scala-case-classes-in-depth/

////////////List, Array, Map, Set (and More)////////////////////


� List
� Array (and ArrayBuffer)
� Map
� Set

Array: Collection of Same type elements.


Arrays preserve order, can contain duplicates, and are mutable.

scala> val numbers = Array(1, 2, 3, 4, 5,5.7)


numbers: Array[Double] = Array(1.0, 2.0, 3.0, 4.0, 5.0, 5.7)

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> val numbers = List(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)


numbers: List[Int] = List(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
scala> numbers(3) = 10
<console>:9: error: value update is not a member of List[Int]
numbers(3) = 10

//Different ways to create lists

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

scala> val numbers = Set (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)


numbers: scala.collection.immutable.Set[Int] = Set(5, 1, 2, 3, 4)

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

Anda mungkin juga menyukai