-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy path2. Learning Scala - Basics.scala
123 lines (75 loc) · 1.9 KB
/
2. Learning Scala - Basics.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
// Databricks notebook source
val f = (x:Int) => x + 1
// COMMAND ----------
f(7)
// COMMAND ----------
val g = () => 100
// COMMAND ----------
g()
// COMMAND ----------
//Methods
def add(x:Int,y:Int): Int = x + y
add(13,24)
// COMMAND ----------
class FullName( firstname:String, lastname:String){
def name(): String = firstname + lastname
}
// COMMAND ----------
val fullname = new FullName("Awantik","Das")
// COMMAND ----------
fullname.name()
// COMMAND ----------
case class Point(x:Int, y:Int)
// COMMAND ----------
//You can instanciate case classes without new keyword
//case classes are immutable
//Compared by value
val point = Point(1,2)
val anotherPoint = Point(1,2)
// COMMAND ----------
point == anotherPoint
// COMMAND ----------
val new_fullname = new FullName("Awantik","Das")
// COMMAND ----------
//Since normal classes are compared by address
fullname == new_fullname
// COMMAND ----------
//Objects
//They are single instances of their own defination
//Singleton of their own classes
//Define obect using object keyword
object Factory{
private var ctr = 0
def construct(): Int = {
ctr += 1
ctr // No need to write return, automatically return ctr
}
}
// COMMAND ----------
val newCtr = Factory.construct()
println(newCtr)
// COMMAND ----------
val newCtr2 = Factory.construct()
println(newCtr2)
// COMMAND ----------
//Traits are types containing certain fields & methods
trait GreatWall{
def great(name:String): Unit
}
// COMMAND ----------
trait DefaultGreatWall{
def great(name:String): Unit =
println("This is default print")
}
// COMMAND ----------
class MyGreatWall extends DefaultGreatWall
// COMMAND ----------
class NewGreatWall extends GreatWall{
def great(name:String): Unit =
println("This is NewGreatWall print")
}
// COMMAND ----------
val ngw = new NewGreatWall()
// COMMAND ----------
ngw.great("6 feet")
// COMMAND ----------