payal-kothari
6/29/2018 - 10:39 PM

Scala - From "Essential Scala" book

Scala - From "Essential Scala" book

class Person(val firstName: String, val lastName: String) {             // constructor
  def name = firstName + " " + lastName

  def printName(first : String = firstName , last : String = lastName) = println(first + " " + last)        // we are assigning values to parameters in the method declaration only
}


object test {
  def main(args: Array[String]): Unit = {
    val obj = new Person("P", "K")
    obj.printName()
  }
}
object conditional {

  def conditional : String = {
    if (1 < 2)
      "Yes"                            // diff from Java,    in scala if-else are expressions and they can "return" "any type" of values
    else
      "No"
  }

  def main(args: Array[String]): Unit = {
    print(conditional)
  }
  
}
class Person(val firstName: String, val lastName: String) {     // we have to write "val" here, unlike the second method
  def name = firstName + " " + lastName
}


//////////     OR    ////////////////////

//class Person(first: String, last: String) {
//  val firstName = first
//  val lastName = last
//  val name = firstName + " " + lastName
//
//}



object test {
  def main(args: Array[String]): Unit = {
    val obj = new Person("P", "K")
    println(obj.name)

    val ibj2 = new Person("A", "B")
    print(ibj2.name)
  }
}
// "def a" and "def c" are methods 
// methods are executed for every separate call

// "val b" val so it will be executed only in the beginning and after that for every call the stored value will be used

object argh {

  def a = {
    println("a")
    1
  }

  val b = {                 // because this is "val", it will be executed first, and it will store the value => "3" , and now on whenever we use this val , it will return the stored value i.e "3"
    println("b")
    a + 2
  }

  def c = {
    println("c")
    a
    b + "c"
  }

  def main(args: Array[String]): Unit = {
    println(b)                        // here the "val b"is already executed, so it returns "3"
    print(argh.c + argh.b + argh.a)
  }

}


// output :
//    b
//    a
//    3
//    c
//    a
//    a
//    3c31