Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I define an anonymous generic Scala function?

Let's say I have this:

val myAnon:(Option[String],String)=>String = (a:Option[String],defVal:String) => {
  a.getOrElse(defVal)
}

Don't mind what the function does. Is there anyway of making it generic, so I can have an Option[T]?

like image 581
Geo Avatar asked Mar 31 '10 16:03

Geo


People also ask

How do you declare anonymous function in Scala?

In Scala, An anonymous function is also known as a function literal. A function which does not contain a name is known as an anonymous function. An anonymous function provides a lightweight function definition. It is useful when we want to create an inline function.

How do you define an anonymous function?

An anonymous function is a function that is not stored in a program file, but is associated with a variable whose data type is function_handle . Anonymous functions can accept multiple inputs and return one output. They can contain only a single executable statement.

How do you define a function in Scala?

In scala, functions are first class values. You can store function value, pass function as an argument and return function as a value from other function. You can create function by using def keyword. You must mention return type of parameters while defining function and return type of a function is optional.

How do I use generics in Scala?

Type-Safety With Generic ClassesWhen declaring a class in Scala, we can specify type parameters. We use square brackets to surround these type parameters. For example, we can declare class Foo[A]. The placeholder A can then be used in the body of the class to refer to the type.


2 Answers

To summarize from that answer: No, you can't make anonymous functions generic, but you can explicitly define your function as a class that extends one of the Function0, Function1, Function2, etc.. traits and define the apply function from those traits. Then the class you define can be generic. Here is the excerpt from the original article, available here:

scala> class myfunc[T] extends Function1[T,String] {
     |     def apply(x:T) = x.toString.substring(0,4)
     | }
defined class myfunc

scala> val f5 = new myfunc[String]
f5: myfunc[String] = <function>

scala> f5("abcdefg")
res13: java.lang.String = abcd

scala> val f6 = new myfunc[Int]
f6: myfunc[Int] = <function>

scala> f6(1234567)
res14: java.lang.String = 1234
like image 200
Jeremy Bell Avatar answered Sep 27 '22 15:09

Jeremy Bell


I don't think anonymous functions can have type parameters. See this answer for details.

like image 30
Ben Lings Avatar answered Sep 27 '22 16:09

Ben Lings