Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make lambda functions generic in Scala? [duplicate]

As most of you probably know you can define functions in 2 ways in scala, there's the 'def' method and the lambda method...

making the 'def' kind generic is fairly straight forward

def someFunc[T](a: T) { // insert body here

what I'm having trouble with here is how to make the following generic:

val someFunc = (a: Int) => // insert body here

of course right now a is an integer, but what would I need to do to make it generic?

val someFunc[T] = (a: T) => doesn't work, neither does val someFunc = [T](a: T) =>

Is it even possible to make them generic, or should I just stick to the 'def' variant?

like image 475
Electric Coffee Avatar asked Jun 28 '13 20:06

Electric Coffee


2 Answers

As Randall Schulz said, def does not create a function, but a method. However, it can return a function and this way you can create generic functions like the identity function in Predef. This would look like this:

def myId[A] = (a: A) => a

List(1,2,3) map myId
// List(1,2,3)

List("foo") map myId
// List("foo")

But be aware, that calling myId without any type information infers Nothing. In the above case it works, because the type inference uses the signature of map, which is map[B](f: A => B) , where A is the type of the list and B gets infered to the same as A, because that is the signature of myId.

like image 79
drexin Avatar answered Oct 18 '22 09:10

drexin


I don't believe it's possible. You can look at this previous post for more details:

How can I define an anonymous generic Scala function?

The only way around it (as one of the answers mentions) is to extend something like FunctionX and use a generic at the class level and then use that in the override of the apply function.

like image 23
cmbaxter Avatar answered Oct 18 '22 08:10

cmbaxter