++ == extends
:+ == append
>> def mult(x: Int, y: Int) = x*y
>> val tmp = mult(2, _: Int)
>> tmp(3)
>> Int = 6
>> def mult(x: Int)(y: Int) = x * y
>> val f = mult(2) _ // or mult(2)(_)
>> f(3)
>> Int = 6
>> def mult(x: Int, y: Int) = x*y
>> val currMult = (mult _).curried
>> val f = currMult(2)
>> f(3)
>> Int = 6
>> val f = (x: Int) => x+1
>> f(2)
>> Int = 3
- Functions with multiple argument : def f(arg: String*) = { args.map {arg => arg.capitalize}}
- Methods are just functions that can access the state of the class.
- Diff b/w function & method:
val f = () => 100 def m1() = 100
functiondo not get invoked when its name is used. Method get invoked. So->
Function:
>> f >> () => Int = <function0> >> f() //now it get invoked
Method:
>> m1()
>> Int = 100
>> m1
>> Int = 100
In simpler terms, method get executed and return the result whereas, function only get replaced by its content.
- We can provide method when function is expected because methd automatically get conerted into a function
Convert a method into a function:
>> def inc(x: int) = x + 1
>> val f = inc(_) // or inc _
>> f(3)
Traits are like interface. An abstract class can be used insted of a trait but use trait because:
- A class can extend multiple traits
- If a constructor is required use abstract class because abstract class can take constructor, traits can't.
String methods: http://www.tutorialspoint.com/scala/scala_strings.htm
>> var z = new Array[String](3)
>> z(0) = "A"
>> var z = Array("A", "B", "C")
>> import Array._
>> //concat two arrays
>> concat(arr1, arr2)
>> //array with range
>> range(1, 10)
>> range(1, 10, 2)
>> range(10, 1, -2)
Array methods: http://www.tutorialspoint.com/scala/scala_arrays.htm
>> //write
>> val writer = new io.PrintWriter(new io.File("file.txt"))
>> writer.write("Hello! World")
>> writer.close()
>> //read
>> io.Source.fromFile("file.txt").foreach(println)
Read user input from terminal:
>> console.readLine
- PartialFunction : trait (kind of interface in other languages)
- Partial function must implement isDefined() and apply() methods.
- isDefinedAt contains the condition when this method will be true.
- apply implements the operation
- We can chain the partial function and the correct function will be called when isDefinedAt returns true
- orElse is used while chaining the functions
- result of partial function can have andThen function (sort of like finally block)
- andThen can contains its seperate chain of logic: something like (1 orElse 0) andThen (1 orElse 0 orElse 1)
- More Info: http://scala-exercises.47deg.com/koans#partialfunctions
** Partial function can be implemented using case statement **
- When case is used isDefinedAt and apply are automatically created.