vivman vivman - 25 days ago 10
Scala Question

Scala-pass value to the function as parameter

I am beginner in scala,i have created two functions.I need to pass output of time function to the input to delayed function.I need to pass b value 5 to delayed function as parameter.

object Demo {

def main(args: Array[String]) {

delayed(time());


}

def time() = {

println("Getting time in nano seconds")

val b=5

return b

}

def delayed( b: => Long ) = {

println("In delayed method")

val a=b+10000

println("Param: " + a)

}

}

Answer

I believe this what you are going for:

object Demo {

   def main(args: Array[String]) {
        delayed(time());
   }

   def time(): Long = {
      println("Getting time in nano seconds")
      5L
   }

   def delayed(b: Long): Unit = {
      println("In delayed method")
      val a = b + 10000
      println(s"Param: $a")
   }
}

Note how types are declared with a colon(:), the use of string interpolation (s"") and how there is no need for a return statement (the last line executed in the block is returned).