Scala Basics
Goal: Understand expressions, variables, types, and type inference in Scala 2.
1. Expressions
An expression produces a value.
println(10 + 20)
println("Hello, Scala!")Output
30
Hello, Scala!
Remember:Arithmetic operations, method calls, and string values can all be expressions.
2. val vs var
Use val for a value that cannot be reassigned. Use var when reassignment is required.
val name = "Deepak"
var age = 30
age = 31
println(name)
println(age)Output
Deepak
31
val prevents reassignment of the variable; it does not automatically make every referenced object immutable.
Best practice: Prefer val unless you specifically need reassignment.
3. Type Inference
Scala can infer a variable's type from its initial value.
val name = "Deepak" // String
val age = 30 // Int
val salary = 50000.0 // DoubleYou can also declare the type explicitly:
val age: Int = 30
Both approaches are valid.
Remember: Scala is statically typed, even when you omit explicit type declarations.
4. Functions
A function accepts input and produces a result.
val add = (a: Int, b: Int) => a + b
println(add(10, 20))Output
30
a: Int and b: Int are parameters.=> separates the parameters from the function body.a + b is the result.
5. Methods
Define a named method using def.
def multiply(a: Int, b: Int): Int = { a * b}
println(multiply(4, 5))Output
20
Key difference: A method is defined with def. A function is a value that can be stored in a variable, passed to another function, or returned.
Key Takeaways
Expressions produce values.
Use
valby default andvarwhen reassignment is necessary.Scala infers types without sacrificing static type checking.
Use
defto define methods.Functions can be stored in values and passed around as data.
