I’m new to Scala, and being able to pass functions to other functions is pretty neat– but can I pass an arbitrary function reference to another function? The arity of said functional parameter will be fixed (that said, I’m also curious about whether you can pass a function with arbitrary arity as well). I keep getting tripped up on type errors. I’ve tried using Any but it doesn’t seem to help.
E.g., I have the code below:
class CodeRunner(val user_defined: (Int) => Unit) {
def run(input: Int) = {
user_defined(input)
}
}
def arbitrary_code(input: Int) = { println("Running with input " + input) }
val d1 = new CodeRunner(arbitrary_code)
d1.run(4)
And I get:
Running with input 4
Now, let’s say that I want to pass the following function instead:
def arbitrary_code(input: String) = { println("Running with input " + input) }
How can I change my CodeRunner class to handle both?
Generic types allow you to define a class with a placeholder type that gets specified when an object gets instantiated. The compiler is happy because it can make sure that everything is type safe, and you’re happy because you can instantiate the object and pass in arbitrary types for the value.
To use a generic type with your class, you could modify it like this:
The [T] after “class CodeRunner” is the important part — it defines that there is a generic type T (you could replace T with another capital letter, etc.) which will be used within the class definition.
So, if you define a method:
and then pass it in:
… the compiler then says “aha, for this instance of CodeRunner the generic type T is a string”. And if you invoke
the compiler will be happy, but won’t let you pass in d1.run(4).