You can try the following commands in your Atom
Terminal. Make sure Spark
is launched priorly.
Your first Scala script
scala> printf("%s is a string, %d is an integer, %f is a float", "Hello Scala!", 12, 34.254)
- Integers (Whole)
scala> 100
res0: Int = 100
- Doubles (Floating Point)
scala> 2.5
res1: Double = 2.5
Addition
scala> 1 + 1
res2: Int = 2
Subtraction
scala> 2 - 1
res3: Int = 1
Multiplication
scala> 2 * 5
res4: Int = 10
Division with Integers (Classic)
scala> 1 / 2
res5: Int = 0
Division with Doubles (True)
scala> 1.0/2
res6: Double = 0.5
scala> 1/2.0
res7: Double = 0.5
Exponents
scala> math.pow(4,2)
res36: Double = 16.0
Modulo (Remainder)
scala> 10 % 4
res8: Int = 2
scala> 9 % 4
res9: Int = 1
You can call back results
scala> res0
res10: Int = 100
Order of Operations with Parenthesis
scala> (1 + 2) * (3 + 4)
res11: Int = 21
scala> 1 + 2 * 3 + 4
res12: Int = 11
Convert 3 feet to meters using scala
scala> 3 * 0.3048
res13: Double = 0.9144000000000001
scala> true
res21: Boolean = true
scala> false
res22: Boolean = false
scala> 1 > 2
res23: Boolean = false
scala> 2 < 1
res24: Boolean = false
scala> 3 >= 1
res27: Boolean = true
scala> 3 <= 3
res28: Boolean = true
scala> 2 == 1
res25: Boolean = false
scala> 2 != 1
res26: Boolean = true
Printing
scala> println("hello")
hello
Concatenation
scala> val fairwell = "Good" + "Bye"
fairwell: String = GoodBye
Repeating
scala> val repeat = "Dance!"*5
repeat: String = Dance!Dance!Dance!Dance!Dance!
String Length
scala> val st = "hello"
st: String = hello
scala> st.length()
res14: Int = 5
Inserting Objects
scala> val name = "Jose"
name: String = Jose
String Interploation
scala> val greet = s"Hello ${name}"
greet: String = Hello Jose
printf
scala> printf("A string: %s , an integer %d, a float %f","hi",10,2.5)
A string: hi , an integer 10, a float 2.500000
scala> printf("A string: %s , an integer %d, a float %1.2f","hi",10,2.5)
A string: hi , an integer 10, a float 2.50
'f' Interploation
scala> val greet = f"Hello ${name}"
greet: String = Hello Jose
scala> val greet = f"Hello $name"
greet: String = Hello Jose
String Indexing
scala> f"First letter of name is $name%.1s"
res8: String = First letter of name is J
// Regular Expressions
Index Location
scala> val st = "This is a long string"
st: String = This is a long string
scala> st.charAt(0)
res18: Char = T
scala> st.indexOf("a")
res19: Int = 8
Pattern matching
scala> val st = "term1 term2 term3"
st: String = term1 term2 term3
scala> st contains "term1"
res20: Boolean = true
scala> st matches "term1"
res11: Boolean = false
scala> st matches "term1 term2 term3"
res12: Boolean = true
Slicing
scala> val st = "hello"
st: String = hello
scala> st slice (0,2)
res2: String = he
scala> st slice (2,st.length)
res4: String = llo
An ordered sequence of values can be of multiple data types
scala> val my_tup = (1,2,"hello",23.2,true)
my_tup: (Int, Int, String, Double, Boolean) = (1,2,hello,23.2,true)
Can also be nested
scala> (3,1,(2,3))
res46: (Int, Int, (Int, Int)) = (3,1,(2,3))
Accessing elements with ._n notation
Indexing starts at 1
scala> val greeting = my_tup._3
greeting: String = hello
scala> my_tup._1
res37: Int = 1
General Format
val <name>: <type> = <literal>
var <name>: <type> = <literal>
var or val determines whether it is a variable or a value.
Values (val) are Immutable.
Variables (var) can be reassigned.
scala> var myvar: Int = 10
myvar: Int = 10
scala> val myval: Double = 2.5
myval: Double = 2.5
Reassignments
Fails for different data type
scala> myvar = "hello"
<console>:12: error: type mismatch;
found : String("hello")
required: Int
myvar = "hello"
Works for same data type and being a var
scala> myvar = 200
myvar: Int = 200
Values can not be reassigned!
scala> myval = 2.5
<console>:12: error: reassignment to val
myval = 2.5
Creating variables and values without types:
Scala can infer data types
scala> val c = 12
c: Int = 12
scala> val s = "my string"
s: String = my string
Valid Names
scala> val my_string = "Hello"
my_string: String = Hello
Not Recommended, but possible
scala> val `my.string` = "hello"
my.string: String = hello
InValid Names
scala> val 2strings = "hello hello"
<console >:1: error: Invalid literal number
val 2strings = "hello hello"
scala> val my.string = "hello"
<console>:11: error: not found: value my
val my.string = "hello"
Collection of variables
Should I use a list or an array?
What is the difference?
Resource link:
http://stackoverflow.com/questions/2712877/difference-between-array-and-list-in-scala
scala> val arr = Array(1,2,3)
arr: Array[Int] = Array(1, 2, 3)
scala> val arr = Array("a","b","c")
arr: Array[String] = Array(a, b, c)
Range
Use of range() method to generate an array containing
a sequence of increasing integers in a given range.
scala> Array.range(0,10)
res64: Array[Int] = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
scala> Array.range(0,10,2)
res65: Array[Int] = Array(0, 2, 4, 6, 8)
Or just call Range with a capital R
scala> Range(0,5)
res1: scala.collection.immutable.Range = Range(0, 1, 2, 3, 4)
scala> Range(0,10,2)
res2: scala.collection.immutable.Range = Range(0, 2, 4, 6, 8)
Lists are an immutable sequence of elements
Basic List of Numbers
scala> val evens = List(2,4,6,8,10,12)
evens: List[Int] = List(2, 4, 6, 8, 10, 12)
Indexing Items (Starts at zero)
scala> evens(0)
res0: Int = 2
scala> evens(1)
res1: Int = 4
Head and Tail
scala> evens.head
res3: Int = 2
scala> evens.tail
res4: List[Int] = List(4, 6, 8, 10, 12)
scala> evens
res5: List[Int] = List(2, 4, 6, 8, 10, 12)
Element Types
Any
scala> val my_list = List("a",2,true)
my_list: List[Any] = List(a, 2, true)
Nested
scala> val my_list = List(List(1,2,3),List(4,5,6))
my_list: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6))
Double and Int
scala> val my_list = List(1,2,3.0)
my_list: List[Double] = List(1.0, 2.0, 3.0)
List of Tuple Pairs
scala> val my_list = List(("a",1),("b",2),("c",3))
my_list: List[(String, Int)] = List((a,1), (b,2), (c,3))
List Operations
scala> val my_list = List(3,6,1,7,10)
my_list: List[Int] = List(3, 6, 1, 7, 10)
scala> my_list.sorted
res7: List[Int] = List(1, 3, 6, 7, 10)
scala> my_list.size
res8: Int = 5
scala> my_list.max
res9: Int = 10
scala> my_list.min
res39: Int = 1
scala> my_list.sum
res40: Int = 27
scala> my_list.product
res41: Int = 1260
Using drop for slicing
scala> val x = List(1,2,3,4)
x: List[Int] = List(1, 2, 3, 4)
scala> x.drop(2)
res3: List[Int] = List(3, 4)
scala> x.takeRight(3)
res4: List[Int] = List(2, 3, 4)
// Use Tab to explore the other methods.
(Key,Value) Pair Storage aka Hash Table or Dictionary
scala> val mymap = Map(("a",1),("b",2),("c",3))
mymap: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c
-> 3)
Lookups
scala> mymap("a")
res12: Int = 1
None if not present
scala> mymap get "b"
res15: Option[Int] = Some(2)
Temp additions on immutable
scala> mymap + ("z"->99)
res19: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c
-> 3, z -> 99)
Mutable maps
scala> val mymutmap = collection.mutable.Map(("x",1),("y",2),("z",3))
mymutmap: scala.collection.mutable.Map[String,Int] = Map(z -> 3, y -> 2,
x -> 1)
Permanent Additions
scala> mymutmap += ("new"->999)
res29: mymutmap.type = Map(z -> 3, y -> 2, x -> 1, new -> 999)
scala> mymutmap
res30: scala.collection.mutable.Map[String,Int] = Map(z -> 3, y -> 2, x -
> 1, new -> 999)
A few useful methods
scala> mymap.keys
res34: Iterable[String] = Set(a, b, c)
scala> mymap.values
res35: Iterable[Int] = MapLike(1, 2, 3)
Set is a collection that contains no duplicate elements.
There are two kinds of Sets, the immutable and the mutable.
Examples
scala> val s = Set()
s: scala.collection.immutable.Set[Nothing] = Set()
scala> val s = Set(1,2,3)
s: scala.collection.immutable.Set[Int] = Set(1, 2, 3)
scala> val s = Set(1,1,2,2,2,3,3,3)
s: scala.collection.immutable.Set[Int] = Set(1, 2, 3)
Mutable Sets
scala> val s = collection.mutable.Set(1,2,3)
s: scala.collection.mutable.Set[Int] = Set(1, 2, 3)
scala> s += 4
res50: s.type = Set(1, 2, 3, 4)
scala> s
res51: scala.collection.mutable.Set[Int] = Set(1, 2, 3, 4)
scala> s.add(5)
res52: Boolean = true
scala> s
res53: scala.collection.mutable.Set[Int] = Set(1, 5, 2, 3, 4)
Set Operations
scala> s.max
res54: Int = 5
scala> s.min
res55: Int = 1
Cast to Set
scala> val mylist = List(1,2,3,1,2,3)
mylist: List[Int] = List(1, 2, 3, 1, 2, 3)
scala> mylist.toSet
res59: scala.collection.immutable.Set[Int] = Set(1, 2, 3)
// Looping an integer
for(item <- List(1,2,3)){
println(item)
}
// Looping an array
for(item <- Array.range(0,5)){
println(item)
}
```r
// Looping a set
for(item <- Set(2,4,9,1,3)){
println(item)
}
// Looping with If Else
// for loop and else if script
for(num <- Range(0,10)){
if(num%2 == 0){
println(s"$num is even")
}else{
println(s"$num is odd")
}
}
// Looping from a list and retrieving one or more results
val names = List("Beerus", "Champa", "Karin", "Kaio", "Dende", "Dodoria")
for(name <- names){
if(name.startsWith("D")){
println(s"$name starts with a D")
}
}
// Looping with a variable
var x = 0
while(x < 5){ // boolean condition
println(s"x is currenly $x")
println("x is still less than 5, adding 1 to x")
x = x+1 // adding 1 to x and iterating until we reach 5
println(s"x is currenly $x")
}
a.) Create a ifelse.scala file in Atom
b.) launch your spark session :load
c.) :load
your file with the following command: // load: url-path/ifelse.scala
- COMPARISON operators - one condition
// if else - script 1
val x = "goku"
if(x.endsWith("b")){
println("value of x ends with b")
}else{
println("value of x does not end with b")
}
// if else - script 2
val person = "Champa"
if(person == "Beerus"){
println("Your Majesty Beerus, this is your bento!")
}else{
println("You can't have a bento, sorry!")
}
- LOGICAL operators - multiple conditions
// if else - script 3
// AND operator - if both conditions are true, program will return "true", if not it will return "false"
println((1 == 2) && (2 == 2)) // && means "AND"
println((4 == 4) && ("b" == "b"))
// OR operator - if one of both conditions is true, program will return "true", if not it will return "false"
println((4 == 3) || ("e" == "e")) // "||" means "OR"
// NOT operator - if condition is not "true", program will return "false"
print(!(1 == 1)) // "!" biaises the results and program returns "false" in that case
object Reverse {
def apply (s: String): String =
s.reverse
}
π΄ See output

Array (1, 2, 3, 4, 5, 6, 7, 8, 9)
π΄ See output

case class Time(hours: Int = 0, minutes: Int = 0)
π΄ See output

List ("Goten", "Trunks", "Gotenks")
res0.map(lang => lang + "#")
res0.flatMap (lang => lang + "#")
π΄ See output

List ("Goku", "Vegeta", "Broly", "Freezer")
res0.filter(lang => lang.contains("e"))
π΄ See output

π΄ See output

π΄ See output

res0.exists(num => num == 12)
π΄ See output

val fighter1 = K9("Trunks", "Goten Trunks Fusion")
fighter1
val fighter2 = fighter1.copy()
fighter2
π΄ See output
