score:24
There are at least two ways you can do it, depending on where exactly you want to pass the argument in. The first way is where you keep main
like you had it.
object Timer {
def oncePerSecond(callback: => Unit) {
while (true) { callback; Thread sleep 1000 }
}
def timeFlies(x: Int) {
println("time flies like an arrow...")
}
def main(args: Array[String]) {
oncePerSecond(timeFlies(5))
}
}
The other method is to pass the parameter in at the point of the callback, like this:
object Timer {
def oncePerSecond(callback: (Int) => Unit) {
val x = 5
while (true) { callback(x); Thread sleep 1000 }
}
def timeFlies(x: Int) {
println("time flies like an arrow...")
}
def main(args: Array[String]) {
oncePerSecond(timeFlies)
}
}
Note that timeFlies
has the signature (Int) => Unit
, but timeFlies(5)
has the signature => Unit
, because of partial application. This basically means you can apply the parameter to automatically create a function that takes fewer parameters. oncePerSecond
needs to know in its signature if you've already applied the Int
parameter to the callback or not.
Both methods are useful for different use cases. The first way lets oncePerSecond
not have to know about the callback's parameters. The second way lets you change the value of x
every time through the loop if you want.
score:0
The parameter callback: () => Unit
is a zero-parameter function that returns Unit
. You should make it call-by-name parameter (something that evaluates to Unit
):
def oncePerSecond(callback: => Unit) = ...
score:0
Passing the function as an argument
def function1(callback: Int => Unit): Unit = {
// do something
}
def callback_function(x: Int): Unit = {
// do something
}
function1(callback_function)
If you want to pass reference of the function to a variable you can do the following...
let say we have function..
def handleLogic(x: Int): Unit => {
// do something
}
val method = handleLogic _
or
val method = handleLogic(_)
score:2
oncePerSecond(() => timeFlies(5))
or
def oncePerSecond(callback: => Unit) {...
score:3
The return type of timeFlies
will be Unit
, not Function
. Perhaps you meant:
oncePerSecond(() => timeFlies(5))
Source: stackoverflow.com
Related Query
- Scala Passing Function with Argument
- Is there a way to call a function defined using `val` in Scala with the whole curly brace block as an argument and not the final result of that block?
- Scala Implicit parameters by passing a function as argument To feel the adnvatage
- scala passing function with underscore produces a function not a value
- Passing a function reference with any arguments to another function in Scala
- How to implement generic function in Scala with two argument types?
- passing a function with type parameter as argument
- Passing Scala Map as an argument to a function takes too much time
- Scala : Overloaded function with PartialFunction in argument
- Scala currying with function argument
- Scala Spark function with generic Dataset[T] argument and also returns Dataset[T]?
- scala lifting function having with a collection as argument
- Call doAnswer with function as argument in scala play 2.4
- In Scala how to curry existing function with single argument and pass to a higher order function?
- Scala :Returning a Function with variable argument from another function
- Passing a function to an argument in Scala
- Scala currying with three argument function
- Passing function with Subclass as argument to function which takes any function with Super class as parameter
- How to partial mock a function with function as an argument in Scala using Mockito
- Trouble passing application argument to spark-submit with scala
- Scala Currying: Overriding function with an empty argument by a partial function
- Passing List as argument in spark scala function gives error
- Writing tests to verify passing a function as argument in Scala
- Defining a function with multiple implicit arguments in Scala
- Functions without arguments, with unit as argument in scala
- Matching function literals with quasiquotes in Scala
- Passing elements of a List as parameters to a function with variable arguments
- Applying an argument list to curried function using foldLeft in Scala
- Scala Function.tupled and Function.untupled equivalent for variable arity, or, calling variable arity function with tuple
- Why does this Scala function compile when the argument does not conform to the type constraint?
More Query from same tag
- How to do recursive codecs in argonaut.io?
- Json Writes in Play 2.1.1
- Sending binary data multiple times using Sockets in Java/Android
- Could not import the newly generated play framework project into IntelliJ IDEA 15
- scala: best way to merge two mutable maps of mutable sets
- How to call function from hashmap in Scala
- Why are case objects serializable and case classes not?
- Scala - fromPublisher is not a member of object akka.stream.scaladsl.Source
- How can I publish my scala play project without application.conf?
- How to call Databricks dbutils using Scala Reflection / Mirrors
- Using Play's JSON autoformatting when json property names don't match
- How to check if database and connection to it is working well with hikaripool or quill?
- scala worksheet: reverse typing
- Scala Unix Timestamp to Date
- Scala promise does not work if I encapsulate it in a commodity function
- Use generic spark estimators in Scala
- org.apache.avro.file.DataFileWriter$AppendWriteException: org.apache.avro.AvroRuntimeException: Unknown datum type
- How costly is it to create(or copy) an object?
- How to sum all of the values in the input sequence in parallel?
- Scala variable scope in object
- Difference in behavior with case objects extending traits
- Scala How To Use Map To Store Methods as values
- scala collection functions different ways to call
- How to mock a call-by-name argument (like getOrElse) using ScalaMock?
- Difference in Scala type inference, Eclipse vs. Maven
- In akka-http, do response entities need to be consumed in a sink when the response is anything other than 200?
- Spark scala udf error for if else
- How to use contains method on a 2D array in scala
- Creating generic update function for Slick 3.1.1
- Flatten Parquet File with nested Arrays and StructType Spark Scala