Scala Introduction

Reading Time: 1 minute

Scala Introduction

I am currently taking courses on Scala. My notes are as follows:

Scala basic syntax (variables)

[codesyntax lang=”scala”]

val a = 2 + 5
val b: Int = 6
val s = "My string"
var d = 3

[/codesyntax]

Scala basic syntax (functions)

[codesyntax lang=”scala”]

def mult(d: Int, f: Int): Int = {
 var res: Int = 0;
 res = d + f;
 return res
}

[/codesyntax]

Class Basics
[codesyntax lang=”scala”]

class Ball (d: Double, t: String ){
 require(t != "")
 def this(d: Double) = this(d, "default")
  println("d: " + d + " t: " +t)
 }

new Ball(3.4, "string")

[/codesyntax]

Creating fields in classes
[codesyntax lang=”scala”]

class MyClass(){
  var q = 0
 }

//create two instances
val instA = new MyClass
val instB = new MyClass

//each instance has its own variables 
instA.q = 5 // changed instA's variable
instA.q // res1: Int = 5
instB.q // res1: Int = 0. instB's variable remained the same

[/codesyntax]

Getters and Setters
[codesyntax lang=”scala”]

class MyGetterClass {
 private[this] var q = 0
 def quantity: Int = q // getter
 def quantity_=(b: Int) { q = b} //setters are created with "_"
}

val x = new MyGetterClass
x.quantity // call getter
x.quantity_=(3) // call setter
x.quantity // call getter

[/codesyntax]

Inheritance
[codesyntax lang=”scala”]

class Shape(val height : Double){
 var h: Double = height
 var result: Double = _
 def volume() {
    result = h *h *h
    println("Volume of Shape: " + result)
 }
}

class Cylinder(override val height: Double, val radius: Double) extends Shape(height) {
 var r: Double = radius
 override def volume(): Unit ={
 result = Pi * r * r * h
 println("Volume of Cylinder: " + result)
 }
 }

var shape = new Shape(10)
 shape.volume()

var cylinder = new Cylinder(10,2)
 cylinder.volume()

[/codesyntax]

Leave a Reply

Your email address will not be published. Required fields are marked *