Features
- Runs on JVM
- Scala code is compiled into byte code, and can run on any platform
- Provides interactive mode to the user
- Easy to use, for developers with non-java background
- Highly recommended for parallel processing, as very fast
- Dynamic scripting with static type
- Var name = “test” On execution, identifies it as String
- Var x = 10; On execution, identifies it as int
- Var y = 15.5; On execution, identifies it as float
- Var is mutable
scala> var name ="test"
name: String = test
scala> var x =10
x: Int = 10
scala> var y=115.5
y: Double = 115.5
- Val z = 10
- Val is immutable
- Printf and print (Similar sytax as C)
- Printf(name); It will print the value.
- Printf(“%d”,x); For double
- Printf(“%f”,y); For Float
- scala> printf(name)testscala> print(z)15.5scala> print(cons)15
- We can find number belongs to which type, by simply typing it
- scala> 25res0: Int = 25scala> 5.5res1: Double = 5.5scala> 1234567res2: Int = 1234567
- scala> "tanu"res0: String = tanu
- Preferably use same File name as main Object name
- We can use varaibleName.isValidByte or isValidInt to check the range
- scala> var a = 1234 a: Int = 1234scala> a.isValidByteres0: Boolean = falsescala> a.isValidIntres1: Boolean = true
- Typecasting in Scala is much simpler
Differences from java
- Completely object oriented. Java is not, as it allows primitive data types also, but Scala doesn’t and is completely object oriented.
- Scala makes accessible the interpreter, which provides an interactive communication mode to the user. And makes certain things very easy, like loading a file into HDFS, a matter of one to two lines of code, As opposed to java, which would need 20 lines of code
- JavaScript is dynamic type scripting,
- e.g. var name = “test” It will take it dynamically as string
- Var I = 10 It will take it dynamically as int
- But this makes unit testing difficult. Scala is dynamic scripting with static type.
- Semi-colon not required, only if multiple commands in the same line
Sample script in Scala - Hello World
Scala> vi First.scala
object First{
def main(args:Array[String]){
println("Hello World")
}
}
}
Scala> scala First.scala (Interpretor way of
execution, can be done if byte code is not needed)
Hello world
sh-4.3$ scala First.scala
Hello World
sh-4.3$ scalac First.scala
Scala> scalac First.scala (Converts it into byte code)
Scala> scala First (Executes the bytecode)
sh-4.3$ ls
First$.class First.class First.scala HelloWorld.scala
sh-4.3$ scala First
Hello World
Executing scala byte code on JVM
A compiled scala program (class file) can be run on JVM as java, just adding scala-library.jar. scala> java -cp ./{lib path}/scala-library.jar scala> javap First