Thursday, 7 December 2017

Knowledge About Basic Scala Programs

scala
=====

what is scala?

Scala is a general purpose programming language.

it runs on Java Virtual Machine (JVM). Scala file translates to Java bytecode

It’s a pure object-oriented programming (OOP) language. Every variable is an ob‐
ject, and every “operator” is a method.

We can use java classes or methods in scala



scala installation
==================

java JDK should be installed

scala

https://www.scala-lang.org/download/

Set SCALA_HOME and add in the PATH variable


scala REPL
==========

REPL -  Read Evaluate  Print Loop

The Scala REPL is a tool (scala) for evaluating expressions in Scala.

In interactive mode, the REPL reads expressions at the prompt,
wraps them in an executable template, and then compiles and executes the result.

examples on REPL
================

in Scala , scala defines the datatype of the variables based on the type of data

val - immutable (read only)
var - mutable (read and write)

Variable Type Inference

val x = 10
var y = 20
y = 30

Assigning two variables at a time

val x, y = 1

x + y

print(res3)

val a = Array(1, 2, 3)

a.sum


Scala datatypes
===============

Byte
Short
Int
Long
Float
Double
Char
String
Boolean
Unit
Null
Nothing
Any
AnyRef


intializing the variable with datatype
======================================

val a:Int = 10

val b : Double = 20.0

val c : Float = 20.0f


First program on scala shell
============================

HelloWorld.scala

  object HelloWorld{
      def main(args:Array[String]){
          print("Hello Scala")
      }
  }

HelloWorld.main(Array("123"))


package imports in scala
========================

import java.util._
import org.apache.spark.sql.{DataFrame, SaveMode,}
import org.apache.spark.SparkEnv


classes and objects
===================

To create a launching point for your applications, you have two choices.
First, you can define an object which extends App

object ScalaFirstObject extends App {

  println("Hello First object Scala")
}

// Or you can define an object that contains a main method

object ScalaSecondObject
{
  def main(args: Array[String]): Unit = {

    println("Hello Second object Scala")

  }
}


Singleton objects

// create a singleton
object CashRegister {
  def open { println("opened") }
  def close { println("closed") }
}

// call the CashRegister methods just like static methods
object Main extends App {
  CashRegister.open
  CashRegister.close
}

classes
======

class Point(val xc: Int, val yc: Int) {
   var x: Int = xc
   var y: Int = yc

   def move(dx: Int, dy: Int) {
      x = x + dx
      y = y + dy
      println ("Point x location : " + x);
      println ("Point y location : " + y);
   }
}

object Demo {
   def main(args: Array[String]) {

      val pt = new Point(10, 20);

      // Move to a new location
      pt.move(10, 10);
   }
}


Static methods in Scala
========================

import java.util.Calendar
import java.text.SimpleDateFormat

object DateUtils {

  // as "Wednesday, October 20"
  def getCurrentDate:String = getCurrentDateTime("EEEE, MMMM d")

  // as "6:20 p.m."
  def getCurrentTime: String = getCurrentDateTime("K:m aa")

  // a common function used by other date/time functions
  private def getCurrentDateTime(dateTimeFormat: String): String = {
    val dateFormat = new SimpleDateFormat(dateTimeFormat)
    val cal = Calendar.getInstance()
    dateFormat.format(cal.getTime())
  }

}


Strings in scala
================

Everthing is treated as object

1. "Hello, scala".getClass.getName

Scala String is a Java String, so you can use all the normal Java string methods.

2. val s = "Hello, world"

3. s.length // to find the length of the string

4. val s = "Hello" + " world" // normally u should assign hello and world in seperate variables

5. "hello".foreach(println) // to iterate the characters of the string

6. for (c <- "hello") println(c) // You can treat a String as a sequence of characters in a for loop

7. s.getBytes.foreach(println) // You can also treat it as a sequence of bytes

8. val result = "hello world".filter(_ != 'l') // to filter 'l' character

9. "scala".drop(2).take(2).capitalize

//testing String equality

10. val s1 = "Hello" , val s2 = "Hello" , val s3 = "H" + "ello"

  s1 == s2
  s1 == s3

11. val s4: String = null
    s3 == s4
    s4 == s3

12. val s1 = "Hello" , val s2 = "hello"

    s1.toUpperCase == s2.toUpperCase

13. val s1: String = null
    val s2: String = null

    s1.toUpperCase == s2.toUpperCase // throws Null pointer Exception

14. val a = "Marisa" , val b = "marisa"
    a.equalsIgnoreCase(b)


// Creating Multiline Strings

15. val foo = """This is a
                multiline String"""

16. val speech = """Four score and |
                  seven years ago""".stripMargin

17. val speech = """Four score and #
                seven years ago""".stripMargin('#')

18. val speech = """Four score and
|seven years ago
|our fathers""".stripMargin.replaceAll("\n", " ")  // To convert this multiline string into one continuous line


19. val s = """This is known as a
|"multiline" string
|or 'heredoc' syntax.""". stripMargin.replaceAll("\n", " ") // includes single quotes and convert into single line


//Splitting Strings

20. "hello world".split(" ") // result is Array[String]

21. "hello world".split(" ").foreach(println) // prints sequentially

22. val s = "eggs, milk, butter, Coco Puffs"
    s.split(",")
    s.split(",").map(_.trim)

23. "hello world, this is Al".split("\\s+")

24. "hello world".split(" ") // split with a String argument

25. "hello world".split(' ') // split with a Char argument

// Substituting Variables into Strings


26. val name = "Fred"
    val age = 33
    val weight = 200.00

    println(s"$name is $age years old, and weighs $weight pounds.")  // s is a method and also string interpolation

     string interpolation functionality was not there Prior to version 2.10

    println(s"Age next year: ${age + 1}") // include expressions while substituting

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


//pending
27. case class Student(name: String, score: Int) // You’ll also need to use curly braces when printing object fields
    val hannah = Student("Hannah", 95)
    println(s"${hannah.name} has a score of ${hannah.score}")

    println(s"$hannah.name has a score of $hannah.score") // without curly braces will not work

28.
println(f"$name is $age years old, and weighs $weight%.2f pounds.") //  f string interpolator

println(f"$name is $age years old, and weighs $weight%.0f pounds.")

// Processing a String One Character at a Time

29. val upper = "hello, world".map(c => c.toUpper)

30. val upper = "hello, world".map(_.toUpper)

31. val upper = "hello, world".filter(_ != 'l').map(_.toUpper)

32. for (c <- "hello") println(c)

33. val upper = for (c <- "hello, world") yield c.toUpper

Adding yield to a for loop essentially places the result from each loop iteration into a temporary holding area.
When the loop completes, all of the elements in the holding area are returned as a single collection.

34. val result = for {
      c <- "hello, world" if c != 'l'
    } yield c.toUpper


35. hello".foreach(println) // Scala treats a string as a sequence of characters

36. "HELLO".map(c => (c.toByte+32).toChar)

37. "HELLO".map{ c =>
      (c.toByte+32).toChar
    }

38. def toLower(c: Char): Char = (c.toByte+32).toChar // write your own method that operates on a character

39.  "HELLO".map(toLower) // use that method with map

40. val s = "HELLO" , for (c <- s) yield toLower(c)

// Finding Patterns in Strings

41. val numPattern = "[0-9]+".r
    val address = "123 Main Street Suite 101"
    val match1 = numPattern.findFirstIn(address)
    val matches = numPattern.findAllIn(address)
    matches.foreach(println)
    val matches = numPattern.findAllIn(address).toArray

// Replacing Patterns in Strings

42. val address = "123 Main Street".replaceAll("[0-9]", "x")
    val regex = "[0-9]".r
    val newAddress = regex.replaceAllIn("123 Main Street", "x")
    val result = "123".replaceFirst("[0-9]", "x")
    val regex = "H".r
    val result = regex.replaceFirstIn("Hello world", "J")

// Accessing a Character in a String

43 "hello".charAt(0) // you could use the Java charAt method
    "hello"(0)
    "hello"(1)
    "hello".apply(1) // behind the scenes, Scala converts your code into this

// Add Your Own Methods to the String Class

44.        implicit class StringImprovements(s: String)
          {  def increment = s.map(c => (c + 1).toChar)
          }

      val result = "HAL".increment

// Put the implicit class in an object

45.
 package com.alvinalexander.utils
object StringUtils {
implicit class StringImprovements(val s: String) {
def increment = s.map(c => (c + 1).toChar)
} }


46. package foo.bar
    import com.alvinalexander.utils.StringUtils._
object Main extends App { println("HAL".increment)
}

47. implicit class StringImprovements(val s: String) //the return type of String is made explicit:
      {
          // being explicit that each method returns a String
          def increment: String = s.map(c => (c + 1).toChar)
          def decrement: String = s.map(c => (c − 1).toChar)
          def hideAll: String = s.replaceAll(".", "*")
          }


48.       implicit class StringImprovements(val s: String) //class demonstrates several dif‐ ferent types of string conversion methods
          {
          def increment = s.map(c => (c + 1).toChar)
          def decrement = s.map(c => (c − 1).toChar)
          def hideAll: String = s.replaceAll(".", "*")
          def plusOne = s.toInt + 1 def asBoolean = s match {
          case "0" | "zero" | "" | " " => false
          case _ => true
          } }

  49. "4".plusOne
      "0".asBoolean
      "1".asBoolean




Friday, 1 December 2017

MongoDB Basic Commands

Herei am taking bike as an collection name


1. update 
db.bike.update({"operationCode":"9102124"},{$set:{"operationCode":"9102125"}})


2. sort
   db.bike.find().sort({"_id":-1})

3. Query
db.bike.find().pretty()

4.find
db.bike.find({"priority":4}).pretty()

5. and, or

db.bike.find( { $and:[ {"priority":3},{"priority":4}]}).pretty()

db.bike.find( { $or:[ {"priority":3},{"priority":4}]}).pretty()

6. limit
db.bike.find().limit(2)

7. index
db.bike.ensureIndex({dealerID:1})

8. bulk write
db.bike.bulkWrite([{insertOne:{“customerID”:232}},{deleteOne:{“_id”:433}}])

db.bike.bulkWrite(
      [
         { insertOne :
            {
               "document" :
               {
                  "_id" : 4,                }
            }
         },
         { insertOne :
            {
               "document" :
               {
                  "_id" : 5, 
               }
            }
         },
         { updateOne :
            {
               "filter" : { "customerID" : 24 },
               "update" : { $set : { "customerID" : 2213 } }
            }
         },
         { deleteOne :
            { "filter" : { "customerID" : 24} }
         },
      ]
   );

9. copy to another collection
db.bike.copyTo(appointmentID)

10. count
db.bike.find().count()

11.distinct
db.bike.distinct(“dealerID”)

12. explain
db.bike.explain()

13.validate
db.bike.validate(true)

14.total index size
db.bike.totalIndexSize()

15.total size
db.bike.totalSize()

16.storage size
db.bike.storageSize()

17. stats
db.bike.stats()

18. latency stats
db.bike.latencyStats( { histograms: true } ).pretty()

19. get index
db.bike.getIndexes()

20. create database
use database name

21. create collection 
db.createCollection(“collectionne”)

22 insert data
db.bike.insert({
...     "_id" : "4333”,
...     "repairOrderID" : "",
...     "customerID" : "24",
...     "serviceAdvisorID" : "TEK00",
...     "isWalkin" : false,
...     "appointmentDateTime" : ISODate("2017-09-04T14:30:00.000Z"),
...     "appointmentCreateDate" : ISODate("2017-09-04T08:07:31.552Z"),
...     "appointmentCreatedSource" : "",
...     "appointmentCreatedBy" : "",
...     "advisorNotes" : "",
...     "VIN" : "",
...     "vehicleID" : "73aad8c2-9148-11e7-8000-000000000000",
...     "year" : 2017,
...     "make" : "GMC",
...     "model" : "Sierra 1500",
...     "status" : 0,
...     "serviceSelected" : [],
...     "customerComment" : "",
...     "dealerID" : "5",
...     "isActive" : false,
...     "lastUpdatedByUser" : "",
...     "lastUpdatedByDateTime" : Date(-62135596800000),
...     "lastUpdatedByDisplay" : "",
...     "documentVersion" : 0.0
... })

23 drop database
drop.testdb()

24 drop collection
drop.bike()

25 drop document
db.bike.remove({“_id”:4333})

26 selecting certain fields
db.bike.find({“_id”:”1”}).pretty()

27 select array objects
db.bike.find({“_id”:”3”},{vehicalDamage:{$elemMatch:{“vehicalDamageID”:”1”,”damageType”:”Scratch”}}})







Sunday, 1 October 2017

Scala Basic Question

What is Scala? Is it a Language or Platform? Does it support OOP or FP? Who is the father of Scala?
Scala stands for SCAlable LAnguage. Martin Odersky is the father of Scala.
Scala is a Multi-Paradigm Programming Language, which supports both Object-Oriented and Functional Programming concepts. It is designed and developed by Martin Odersky.
Scala is a Type-Safe Object-Functional Programming JVM Language. Scala runs on JVM(Java Virtual Machine).
Scala is a Hybrid Functional (Object-Oriented and Functional) Programming JVM Language. Scala has a Strong and Statically Type System. In Scala, all types are checked at compile-time.
Is Scala Statically-Typed Language? What is Statically-Typed Language and What is Dynamically-Typed Language? What is the difference between statically typed and dynamically typed languages?
Yes, Scala is a Statically-Typed Language.
Statically-Typed Language means that Type checking is done at compile-time by compiler, not at run-time. The main Advantage of these kinds of Languages is: As a Developer, we should care about writing right code to avoid all compile-time errors. As Compiler checks many of the errors at compile-time, we don’t get much issues or bugs at run-time.
Examples:- Java, Scala, C, C++, Haskell etc.
Dynamically-Typed Language means that Type checking is done at run-time, not at compile-time by compiler. As a compiler won’t check any type checking at compile-time, We can expect more run-time issues or bugs.
Example:- Groovy, JavaScript, Ruby, Python, Smalltalk etc.
Is Scala a Pure OOP Language? Is Java a Pure OOP Language?
Pure Object-Oriented Programming Language means that everything should be an Object.
Java is not a Pure Object-Oriented Programming (OOP) Language because it supports the following two Non-OOP concepts:
·      Java supports primitive data types. They are not objects.
·      Java supports Static members. They are not related to objects.
Yes, Scala is a Pure Object-Oriented Programming Language because in Scala, everything is an Object and everything is a value. Functions are values and values are Objects.
Scala does not have primitive data types and also does not have static members.
Does Scala support all Functional Programming concepts? Does Java 8 support all Functional Programming concepts?
Yes, Scala supports all Functional Programming (FP) concepts. Java 8 has introduced some Functional Programming constructs, but it does NOT support all Functional Programming concepts.
For instance, Java 8 does not support Pattern Matching, Function Currying, Implicits etc.
What are the major advantages of Scala Language? Are there any drawbacks of Scala Language?
If we use Scala Language to develop our applications, we can get the following benefits or advantages and drawbacks:
Advantages of Scala Language:-
·      Simple and Concise Code
·      Very Expressive Code
·      More Readable Code
·      100% Type-Safe Language
·      Immutability and No Side-Effects
·      More Reusable Code
·      More Modularity
·      Do More With Less Code
·      Very Flexible Syntax
·      Supports all OOP Features
·      Supports all FP Features. Highly Functional.
·      Less Error Prone Code
·      Better Parallel and Concurrency Programming
·      Highly Scalable and Maintainable code
·      Highly Productivity
·      Distributed Applications
·      Full Java Interoperability
·      Powerful Scala DSLs available
·      REPL to learn Scala Basics
Drawbacks of Scala Language:-
·      Less Readable Code
·      Bit tough to Understand the Code for beginners
·      Complex Syntax to learn
·      Less Backward Compatibility
NOTE:- We can write Scala Code either more readable or less readable way.
What is the Main drawback of Scala Language?
Apart from many benefits of Scala, it has one major Drawback: Backward Compatibility Issue. If we want to upgrade to latest version of Scala, then we need to take care of changing some package names, class names, method or function names etc.
For instance, If you are using old Scala version and your project is using BeanProperty annotation. It was available in “scala.reflect” like “scala.reflect.BeanProperty” in old versions. If we want to upgrade to new Scala versions, then we need to change this package from “scala.reflect” to “scala.beans”.
What is the main motto of Scala Language?
Like Java’s Motto “Write Once Run Anywhere”, Scala has “Do More With Less” or “Do More With Less Code”Motto.
“Do More With Less” means that we can develop more complex program or logic with less code.
What are the popular JVM Languages available now?
Java, Scala, Groovy and Closure are most popular JVM (Java Virtual Machine) languages.
Scala, Groovy and Closure JVM languages supports both Object-Oriented Programming Features and Functional Programming Features.
Java SE 8 supports all Object-Oriented Programming Features. However, it supports very few Functional Programming Features like Lambda Expressions, Functions, Type Inference, Higher-Order Functions.
Like Java’s java.lang.Object class, what is the super class of all classes in Scala?
As we know in Java, the super class of all classes (Java API Classes or User Defined Classes) is java.lang.Object. In the same way in Scala, the super class of all classes or traits is “Any” class.
Any class is defined in scala package like “scala.Any”.
What is default access modifier in Scala? Does Scala have “public” keyword?
In Scala, if we don’t mention any access modifier to a method, function, trait, object or class, the default access modifier is “public”. Even for Fields also, “public” is the default access modifier.
Because of this default feature, Scala does not have “public” keyword.
What is “Type Inference” in Scala?
Types can be inferred by the Scala Compiler at compile-time. It is known as “Type Inference”. Types means Data type or Result type. We use Types at many places in Scala programs like Variable types, Object types, Method/Function Parameter types, Method/Function return types etc.
In simple words, determining the type of a variable or expression or object etc at compile-time by compiler is known as “Type Inference”.
What are the similarities and differences between Scala’s Int and Java’s java.lang.Integer? What is the relationship between Int and RichInt in Scala?
Similarities between Scala’s Int and Java’s java.lang.Integer:
·      Both are classes.
·      Both are used to represent integer numbers.
·      Both are 32-bit signed integers.
Differences between Scala’s Int and Java’s java.lang.Integer:
·      Scala’s Int class does not implement Comparable interface.
·      Java’s java.lang.Integer class implements Comparable interface.
Java’s Integer is something similar to Scala’s Int and RichInt. RichInt is a final class defined in scala.runtime package like “scala.runtime.RichInt”.
In Scala, the Relationship between Int and RichInt is that when we use Int in a Scala program, it will automatically convert into RichInt to utilize all methods available in that Class. We can say that RichInt is an Implicit class of Int.
What is Nothing in Scala? What is Nil in Scala? What is the relationship between Nothing and Nil in Scala?
In Scala, Nothing is a Type (final class). It is defined at the bottom of the Scala Type System that means it is a subtype of anything in Scala. There are no instances of Nothing.
Use Cases of Nothing In Scala:-
If Nothing does not have any instances, then when do we use this one in Scala Applications?
·      Nil is defined using Nothing (See below for example).
·      None is defined using Nothing.
object None extends Option[Nothing]
·      We can use Nothing as a return type of methods which never return.
·      We can use Nothing as a return type of methods which terminates abnormally.
Nil is an object, which is used to represent an empty list. It is defined in “scala.collection.immutable” package as shown below:
object Nil extends List[Nothing]
Example:-
scala> Nil res5: scala.collection.immutable.Nil.type = List()  scala> Nil.length res6: Int = 0
What is Null in Scala? What is null in Scala? What is difference between Null and null in Scala?
Null is a Type (final class) in Scala. Null type is available in “scala” package as “scala.Null”. It has one and only one instance that is null.
In Scala, “null” is an instance of type scala.Null type.
Example:-
scala> val myNullRef : Null = null myNullRef: Null = null
We cannot assign other values to Null type references. It accepts only ‘null’ value.
Null is a subtype of all Reference types. Null is at the bottom of the Scala Type System. As it is NOT a subtype of Value types, we can assign “null” to any variable of Value type.
Example:-
scala> val myInt : Int = null :10: error: an expression of type Null is ineligible for implicit conversion        val myInt : Int = null

Here type mismatch error. found : Null(null) but required: Int. The implicit conversions between Null and Int are not applicable because they are ambiguous.
What is Unit in Scala? What is the difference between Java’s void and Scala’s Unit?
In Scala, Unit is used to represent “No value” or “No Useful value”. Unit is a final class defined in “scala” package that is “scala.Unit”.
Unit is something similar to Java’s void. But they have few differences.
·      Java’s void does not any value. It is nothing.
·      Scala’s Unit has one value ()
·      () is the one and only value of type Unit in Scala. However, there are no values of type void in Java.
·      Java’s void is a keyword. Scala’s Unit is a final class.
Both are used to represent a method or function is not returning anything.
What is the difference between val and var in Scala?
In Scala, both val and var are used to define variables. However, they have some significant differences.
·      var stands for variable.
·      val stands for value.
·      As we know, variable means changeable and value means constant.
·      var is used to define Mutable variables that means we can reassign values once its created.
·      val is used to define Immutable variables that means we cannot reassign values once its created.
·      In simple Java terminology, var means ‘variable’ and val means ‘final variable’.
What is REPL in Scala? What is the use of Scala’s REPL? How to access Scala REPL from CMD Prompt?
REPL stands for Read-Evaluate-Print Loop. We can pronounce it as ‘ripple’. In Scala, REPL is acts as an Interpreter to execute Scala code from command prompt. That’s why REPL is also known as Scala CLI(Command Line Interface) or Scala command-line shell.
The main purpose of REPL is that to develop and test small snippets of Scala code for practice purpose. It is very useful for Scala Beginners to practice basic programs.
We can access REPL by using “scala” command. When we type “scala” command at CMD Prompt, we will get REPL shell where we can type and execute scala code.
D:\> scala  scala>
What are the Scala Features?
Scala Language supports the following features:
·      Supports both OOP-style(Imperative-Style) and Functional-Style Programming
·      Pure Object-Oriented Programming Language
·      Supports all Functional Features
·      REPL(Read-Evaluate-Print Loop) Interpreter
·      Strong Type System
·      Statically-Typed Language
·      Type Inference
·      Supports Pattern Matching
·      Supports Closures
·      Supports Persistent Data Structures
·      Uses Actor Model to develop Concurrency Applications
·      Interoperable with Java
·      Available all development tools – IDEs, Build Tools, Web Frameworks, TDD and BDD Frameworks
How do we implement loops functionally? What is the difference between OOP and FP style loops?
We know how to implement loops in Object-Oriented style: Using Mutable Temporary variables, update the variable value and use Loop constructs. It is very tedious and unsafe approach. It is not Thread-Safe.
Object-Oriented style uses the following constructs to implement Loops:
·      Loop Constructs
·      Mutability
·      Side Effects
We can implement same Loops differently in Functional way. It is Thread-Safe. We can use the following two techniques to implement the loops in functional style:
·      Recursion
·      Tail-Recursion
·      Immutability
·      No Side-Effects
What is “Application” in Scala or What is Scala Application? What is “App” in Scala? What is the use of Scala’s App?
Scala Application:
In Scala, App is a trait defined in scala package like “scala.App”. It defines main method. If an Object or a Class extends this trait, then they will become as Scala Executable programs automatically because they will inherit main method from Application.
The main advantage of using App is that we don’t need to write main method. The main drawback of using App is that we should use same name “args” to refer command line argument because scala.App’s main() method uses this name.
Example:-
Without Scala App:
object MyApp {     def main( args: Array[String]){         println("Hello World!")     } }
With Scala App:
object MyApp extends App{    println("Hello World!") }
If we observe above two examples, in second example we have not defined main method because we have inherited from Scala App(Application).
Before Scala 2.9, we have scala.Application trait. But it is deprecated by scala.App since Scala 2.9 version.
Does Scala support Operator Overloading? Does Java support Operator Overloading?
Java does not support Operator Overloading. Scala supports Operator Overloading.
The reason is that Java does not want to support some misleading method names like “+*/”. Scala has given this flexibility to Developer to decide which methods/functions name should use.
When we call 2 + 3 that means ‘+’ is not an operator, it is a method available in Int class (or it’s implicit type). Internally, this call is converted into “2.+(3)“.
What is an Expression? What is a Statement? Difference between Expression and Statement?
Expression:
Expression is a value that means it will evaluate to a Value. As an Expression returns a value, We can assign it to a variable.
Example:- Scala’s If condition, Java’s Ternary operator.
Statement:
Statement defines one or more actions or operations. That means Statement performs actions. As it does not return a value, we cannot assign it to a Variable.
Example:- Java’s If condition.
What is the difference between Java’s “If..Else” and Scala’s “If..Else”?
Java’s “If..Else”:
In Java, “If..Else” is a statement, not an expression. It does not return a value and cannot assign it to a variable.
Example:-
 int year;  if( count == 0)     year = 2014;  else     year = 2015;
Scala’s “If..Else”:
In Scala, “If..Else” is an expression. It evaluates a value i.e. returns a value. We can assign it to a variable.
 val year = if( count == 0) 2014 else 2015
NOTE:-Scala’s “If..Else” works like Java’s Ternary Operator. We can use Scala’s “If..Else” like Java’s “If..Else” statement as shown below:
 val year = 0  if( count == 0)     year = 2014   else     year = 2015
Is Scala an Expression-Based Language or Statement-Based Language? Is Java an Expression-Based Language or Statement-Based Language?
In Scala, everything is a value. All Expressions or Statements evaluates to a Value. We can assign Expression, Function, Closure, Object etc. to a Variable. So Scala is an Expression-Oriented Language.
In Java, Statements are not Expressions or Values. We cannot assign them to a Variable. So Java is not an Expression-Oriented Language. It is a Statement-Based Language.
Tell me some features which are supported by Java, but not by Scala and Vice versa?
·      Java does not support Operator Overloading, but Scala supports it.
·      Java supports ++ and — operators , but Scala does not support them.
·      Java has Checked and Unchecked Exceptions, but Scala does not have Checked Exceptions.
·      Scala does not support break and continue statements, but Java uses them.
·      Scala does not have explicit Type casting, but Java supports this feature.
·      Scala supports Pattern Matching, but Java does not.
·      Java uses Primitive Data types, but Scala does not have.
·      Java supports static members, but Scala does not have static members concept.
·      Scala supports Implicits and Traits, Java does not support them.
NOTE:-This list goes beyond one page. However, these are some important points to remember about differences in Scala and Java features to face Scala Interviews.
What is the difference between Function and Method in Scala?
Scala supports both functions and methods. We use same syntax to define functions and methods, there is no syntax difference.
However, they have one minor difference:
·      We can define a method in a Scala class or trait. Method is associated with an object (An instance of a Class). We can call a method by using an instance of a Class. We cannot use a Scala Method directly without using object.
·      Function is not associated with a class or trait. It is defined in a Scala Package. We can access functions without using objects, like Java’s Static Methods.
NOTE:- We will discuss about Class, Trait,Package, Object etc in my coming posts.
How many public class files are possible to define in Scala source file?
In Java, we can define at-most one public class/interface in a Source file. Unlike Java, Scala supports multiple public classes in the same source file.
We can define any number of public classes/interfaces/traits in a Scala Source file.
Like Java, what are the default imports in Scala Language?
We know, java.lang is the default package imported into all Java Programs by JVM automatically. We don’t need to import this package explicitly.
In the same way, the following are the default imports available in all Scala Programs:
·      java.lang package
·      scala package
·      scala.PreDef
How many operators are there in Scala and Why?
Unlike Java and like C++, Scala supports Operator Overloading. Scala has one and only operator that is “=” (equalto) operator. Other than this all are methods only.
For instance 2 + 3, here “+” is not an Operator in Scala. “+” is method available in Int class. Scala Compiler observes 2 and 3 are Integers and tries to find that “+” method in Int class. So Scala Compiler converts “2 + 3” expression into “2.+(3)” and make a call to “+” method on integer object “2” and pass integer object “3” as parameter to “+” method.
Both “2 + 3” and “2.+(3)” are equal. It’s just Scala’s syntactic sugar to write programs in Functional style.
Mention Some keywords which are used by Java and not required in Scala? Why Scala does not require them?
Java uses the following keywords extensively:
·      ‘public’ keyword – to define classes, interfaces, variables etc.
·      ‘static’ keyword – to define static members.
Scala does not required these two keywords. Scala does not have ‘public’ and ‘static’ keywords.
·      In Scala, default access modifier is ‘public’ for classes,traits, methods/functions, fields etc. That’s why, ‘public’ keyword is not required.
·      To support OOP principles, Scala team has avoided ‘static’ keyword. That’s why Scala is a Pure-OOP Langauge. It is very tough to deal static members in Concurrency applications.