Requirements to Run Scala
Ide: There are a couple of IDE to run scala. Depends on your own preference.How do you define Variables in Scala
- Scala doesn't need you to declare type of variables if the compiler can detect the type.
- However if the type can't be inferred automatically you have to provide the type.
var num=10
var x: Int = 5
var lng: Long = 100000000L
var sht: Short = 1
var dbl: Double = 2.50
var flt: Float = 2.50f
var str: String = "Hello Scala"
var bte: Byte = 0xa
var chr: Char = 'D'
These variables are also known as mutable types. Mutable types means its values can be changed. Scala prefers you to use as little mutable types as possible.
Constants
Constants are immutable types. It essentially means that these values can't be changed. Constants are declared in Scala using the val keyword
val x=10x=20 //Wrong.. Will generate an error
Variables with No Initialization
var test:String=_
When the variable is not initialized it's type must be declared
If else construct in Scala
If else construct in scala is similar to java. However if else can also be used as an expression in scala.
val x=10if(x==10) println("X is equal to 10") else println("X is not equal to 10")
println is used for output
Generally it is a good idea to enclose your statements in { } braces.
if(x<10){ println("Value of x ") println("X is less than 10") } else if (x >10) { println("X is greater than 10") } else { println("X is equal to 10") }
Note: You don't need a semicolon to terminate your expression in scala.
Loops
In Scala, loops are not used as often as in other languages. Instead most often the values are processed by applying a function to all values. Its known as functional programming.
Simple Loop
println("Step 1: A simple for loop from 1 to 10 ") for(i <- 1 to 10){ println(s"Loop Number = $i") }
Use "until" instead of "to" to exclude the last iteration.
println("Step 1: A simple for loop from 1 to 10 ") for(i <- 1 until 10){ println(s"Loop Number = $i") }
While Loop
While loop in scala is the same as Java/C++
while (x > 0) { r = r * n x -= 1}
Scala doesn't have ++ and -- increment. Instead use += or -=
Scala Lists
Scala lists are similar to arrays in a sense that they consist the same type of data.
val colors:List[String]=List("red","blue","green") val nums:List[Int]=List(1,2,3,4)
Two Dimensional Lists
val twoDimensional: List[List[Int]] = List( List(1, 0, 0), List(0, 1, 0), List(0, 0, 1) )
Lists are Immutable
Lists have the following methods.
println( "Head of colors : " + colors.head ) println( "Tail of fruit : " + colors.tail ) println( "Check if fruit is empty : " + colors.isEmpty ) println( "Check if nums is empty : " + colors.isEmpty )
- Lists can also be concatenated by List.concat(list1,list2,listn)
- List.fill() method creates a list consisting of zero or more copies of the same element
- List.reverse method reverses all elements of the list
For further info on lists visit https://www.scala-lang.org/api/2.12.3/scala/collection/immutable/List.html