Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a function literal use type parameter in Scala?

Tags:

scala

Given the following definition of a method removeAt that's polymorphic:

def removeAt[T](n: Int, ts: Seq[T]): (Seq[T], T) = ???

How can I declare a list of removeAt-like functions? Can a function literal use type parameter?

How can I make the following compilable and able to contain removeAt?

List[(Int, Seq[_]) => (Seq[_], _)](removeAt)

UPDATE: Why does the following work fine so I can foreach over the list and execute the functions? That's exactly what I needed in the first place.

val solutions = Seq[(Int, Seq[Any]) => (Seq[Any], Any)](
  removeAt
)
like image 935
Jacek Laskowski Avatar asked Nov 29 '13 22:11

Jacek Laskowski


People also ask

How do you pass parameters to a Scala function?

Scala - Functions with Named Arguments Named arguments allow you to pass arguments to a function in a different order. The syntax is simply that each argument is preceded by a parameter name and an equals sign. Try the following program, it is a simple example to show the functions with named arguments.

What kind of parameters are not needed while calling a method in Scala?

A parameterless method is a function that does not take parameters, defined by the absence of any empty parenthesis. Invocation of a paramaterless function should be done without parenthesis.

What is the type of a function in Scala?

Scala functions are first-class values. Scala functions are first-class values. You must mention the return type of parameters while defining the function and the return type of a function is optional. If you don't specify the return type of a function, the default return type is Unit.


1 Answers

The blog post First-class polymorphic function values in shapeless (1 of 3) — Function values in Scala seems to imply that there's no way in "standard" Scala to have polymorphic function values:

We can have first-class monomorphic function values and we can have second-class polymorphic methods, but we can't have first-class polymorphic function values ... at least we can't with the standard Scala definitions.

It looks like we need a library like shapeless.

like image 87
Jacek Laskowski Avatar answered Sep 22 '22 23:09

Jacek Laskowski