I need to have a collection of generic functions, but I can't get it done in the way I like. I created a
List[(Any)=>Unit]
but as soon as I try to insert a function, for example a
String=>Unit
I get an error. How could I declare a generic function collection that does not consider parameter and return values types?
Scala treats functions as first-class data types, as demonstrated throughout this chapter and supported by the notions of higher-order functions, function literals, and function types.
In Scala, functions are first-class citizens because we can do the following things with them: We can use functions as values or like normal variables; we can replace a variable or value with a function. We can assign a function literal to a variable. We can pass one or more functions as another function's parameters.
In Python, functions behave like any other object, such as an int or a list. That means that you can use functions as arguments to other functions, store functions as dictionary values, or return a function from another function.
A programming language is said to have First-class functions when functions in that language are treated like any other variable. For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable.
Functions are contravariant in the intput type parameters, e.g. in your case Function1[-T1,+R]
. This means you can add an instance of Any => Unit
to a List[String => Unit]
but not the other way round. This of course makes sense as you cannot call a function expecting an argument of type String
with an argument of type Any
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With