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]?
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.
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.
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.
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.
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
I don't think anonymous functions can have type parameters. See this answer for details.
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