Object Oriented vs Functional Language

def function1(a:Int)={
(a*2)+4
}
List(55,6,6).map(function1) //function1 is used as input argument just as any Int or String literal.
def function2():Int=>String={
a=>a.toString
}
function2()(5) // Output is val res13: String = 5.
def function1(a:Int):Int = i+1 // referentially transparent
def function1(a:Int):Int = { println(i); i+1 } // Not referentially transparent
How println makes the function referentially not transparent? Calling, function1(1)+function1(1) The result will be 4 and the output will be,
// 1
// 1
Whereas executing, val a= function1(1); a+a; the output will be different,
Result is same as 4 but the output is,
// 1
var a=5
def func3(x:Int)={
a+x
}
func3(5)// Result is 10. Consider you changing the value of a , var a=3
func3(5)// Result is 8.
val functn = (a:Int,b:Int)=> a+ b;functn(5,6).toString; // result is val res1: String = 11. toString is a concrete method available under trait Function2.
val a:Tuple[Int,String]=Tuple(1,"trial") // this is wrong. You will get error. val a:Tuple2[Int,String]=Tuple2(1,"trial") // this works
or
val a=(1,"trial") // this also works
Eg,
def func2(a:Int,b:Int) = a+b
val first=func2(3,_)
first(4) // Result is 7
val second=func2 _
second(3,4) //Result is 7
def func4(implicit a:Int,b:String,c:Double)={
println(a,b,c)
}
implicit val first_arg=5
implicit val second_arg="Hello"
implicit val third_arg=9.0
func4 //The output is,
(5,Hello,9.0)
implicit val first_arg=5
implicit val second_arg="Hello"
implicit val third_arg=9.0
implicit val first_copy=6 // Two implicit Int values are available for the first argument
func4 //Error thrown,
error: ambiguous implicit values:
Implicit functions with implicit type conversions,
implicit def func3(a:Int):String ={
println("I am inside function")
"HEllo!! Welcome Home"
}
100.split("!!") //Result is,
I am inside function
val res2: Array[String] = Array(HEllo, " Welcome Home")
class trial_class(a:String){
def func1 =println(a)
}
implicit def implicit_function(b:Int):trial_class =new trial_class("Check!! Check!!")
5.func1 //Result is,
Check!! Check!!
// Function without currying
def mutilplearguments(a:Int,b:Int,c:Int)= {
a+b*c/100 + a*c/100
}
mutilplearguments(5,2,3) // Result is 5
//Curried Function
def mutilplearguments(a:Int)(b:Int)(c:Int)= {
a+b*c/100 + a*c/100
}
// Curried function (partially applied)
val first=mutilplearguments(5)_;
val second = first(2);
val third= second(3); // Result is 5
val first= mutilplearguments(5)(2)_;
val second=first(3); // Result is 5

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Teepika R M

Teepika R M

AWS Certified Big Data Specialty| Linux Certified Kubernetes Application Developer| Hortonworks Certified Spark Developer|Hortonworks Certified Hadoop Developer