Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: issues using functions as first class objects

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?

like image 639
mariosangiorgio Avatar asked Jul 31 '10 16:07

mariosangiorgio


People also ask

Are functions first class in Scala?

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.

What does it mean that functions are first class citizens in Scala?

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.

Are functions first class objects?

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.

What does it mean when a language treats functions as first class citizens?

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.


1 Answers

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.

like image 145
Moritz Avatar answered Sep 28 '22 16:09

Moritz