Is it possible in scala to have a generic method taking a method as an argument? - scala

I would like to have:
def myMethod[T < ???](f: T): Unit = {
f()
}
The rest of the method is not really important but is it possible to replace ??? by somethind which would make sure T is a method
and if possible to go even further and make sure the return type of T is something defined ?
Like [T < (_*) => Int]
Thank you.

Would defining a type, like in the following trivial example, address your need?
type Fcn = String => Int
def myMethod(s: String, f: Fcn): Unit = {
println(f(s))
}
myMethod("hello", (s: String) => s.length)
// 5

You can use function literals:
def myMethod[A, T](f: A => T) {
f(someAValue)
}
or if you want functions that take no arguments:
def myMethod[T](f: () => T) {
f()
}
But judging by your comments, it seems like you specifically want to reference methods, and query the method for information about itself, which is not a feature of basic Scala. You may be able to do some of that with reflection, but reflection is an area best avoided.

Technically, you can't directly pass a method, since a method is not a value that you can instantiate and pass-around. What is usually passed around is a function instance. And when it appears that you're passing a method, the compiler is actually creating a function instance for you (method lifting or eta-expansion).
But that is not going to work if you're looking to inspect meta data about that method (name, deprecation). For that, you're probably looking for reflection. You can have your method take an instance of java.reflect.Method but that will require that you obtain that at call-site.

Related

Scala by name versus function parameters [duplicate]

What is still unclear for is what's the advantage by-name parameters over anonymous functions in terms of lazy evaluation and other benefits if any:
def func1(a: => Int)
def func2(a: () => Int)
When should I use the first and when the second one?
This is not the copy of What's the difference between => , ()=>, and Unit=>
Laziness is the same in the both cases, but there are slight differences. Consider:
def generateInt(): Int = { ... }
def byFunc(a: () => Int) { ... }
def byName(a: => Int) { ... }
// you can pass method without
// generating additional anonymous function
byFunc(generateInt)
// but both of the below are the same
// i.e. additional anonymous function is generated
byName(generateInt)
byName(() => generateInt())
Functions with call-by-name however is useful for making DSLs. For instance:
def measured(block: ⇒ Unit): Long = {
val startTime = System.currentTimeMillis()
block
System.currentTimeMillis() - startTime
}
Long timeTaken = measured {
// any code here you like to measure
// written just as there were no "measured" around
}
def func1(a: => Int) {
val b = a // b is of type Int, and it`s value is the result of evaluation of a
}
def func2(a: () => Int) {
val b = a // b is of type Function0 (is a reference to function a)
}
An example might give a pretty thorough tour of the differences.
Consider that you wanted to write your own version of the veritable while loop in Scala. I know, I know... using while in Scala? But this isn't about functional programming, this is an example that demonstrates the topic well. So hang with me. We'll call our own version whyle. Furthermore, we want to implement it without using Scala's builtin while. To pull that off we can make our whyle construct recursive. Also, we'll add the #tailrec annotation to make sure that our implementation can be used as a real-world substitute for the built-in while. Here's a first go at it:
#scala.annotation.tailrec
def whyle(predicate: () => Boolean)(block: () => Unit): Unit = {
if (predicate()) {
block()
whyle(predicate)(block)
}
}
Let's see how this works. We can pass in parameterized code blocks to whyle. The first is the predicate parameterized function. The second is the block parameterized function. How would we use this?
What we want is for our end user to use the whyle just like you would the while control structure:
// Using the vanilla 'while'
var i = 0
while(i < args.length) {
println(args(i))
i += 1
}
But since our code blocks are parameterized, the end-user of our whyle loop must add some ugly syntactic sugar to get it to work:
// Ouch, our whyle is hideous
var i = 0
whyle( () => i < args.length) { () =>
println(args(i))
i += 1
}
So. It appears that if we want the end-user to be able to call our whyle loop in a more familiar, native looking style, we'll need to use parameterless functions. But then we have a really big problem. As soon as you use parameterless functions, you can no longer have your cake and eat it too. You can only eat your cake. Behold:
#scala.annotation.tailrec
def whyle(predicate: => Boolean)(block: => Unit): Unit = {
if (predicate) {
block
whyle(predicate)(block) // !!! THIS DOESN'T WORK LIKE YOU THINK !!!
}
}
Wow. Now the user can call our whyle loop the way they expect... but our implementation doesn't make any sense. You have no way of both calling a parameterless function and passing the function itself around as a value. You can only call it. That's what I mean by only eating your cake. You can't have it, too. And therefore our recursive implementation now goes out the window. It only works with the parameterized functions which is unfortunately pretty ugly.
We might be tempted at this point to cheat. We could rewrite our whyle loop to use Scala's built-in while:
def whyle(pred: => Boolean)(block: => Unit): Unit = while(pred)(block)
Now we can use our whyle exactly like while, because we only needed to be able to eat our cake... we didn't need to have it, too.
var i = 0
whyle(i < args.length) {
println(args(i))
i += 1
}
But we cheated! Actually, here's a way to have our very own tail-optimized version of the while loop:
def whyle(predicate: => Boolean)(block: => Unit): Unit = {
#tailrec
def whyle_internal(predicate2: () => Boolean)(block2: () => Unit): Unit = {
if (predicate2()) {
block2()
whyle_internal(predicate2)(block2)
}
}
whyle_internal(predicate _)(block _)
}
Can you figure out what we just did?? We have our original (but ugly) parameterized functions in the inner function here. We have it wrapped with a function that takes as arguments parameterless functions. It then calls the inner function and converts the parameterless functions into parameterized functions (by turning them into partially applied functions).
Let's try it out and see if it works:
var i = 0
whyle(i < args.length) {
println(args(i))
i += 1
}
And it does!
Thankfully, since in Scala we have closures we can clean this up big time:
def whyle(predicate: => Boolean)(block: => Unit): Unit = {
#tailrec
def whyle_internal: Unit = {
if (predicate) {
block
whyle_internal
}
}
whyle_internal
}
Cool. Anyways, those are some really big differences between parameterless and parameterized functions. I hope this gives you some ideas!
The two formats are used interchangeably, but there are some cases where we can use only one of theme.
let's explain by example, suppose that we need to define a case class with two parameters :
{
.
.
.
type Action = () => Unit;
case class WorkItem(time : Int, action : Action);
.
.
.
}
as we can see, the second parametre of the WorkItem class has a type Action.
if we try to replace this parameter with the other format =>,
case class WorkItem1(time : Int, s : => Unit) the compiler will show a message error :
Multiple markers at this line:
`val' parameters may not be call-by-name Call-by-name parameter
creation: () ⇒
so as we have see the format ()=> is more generic and we can use it to define Type, as class field or method parameter, in the other side => format can used as method parameter but not as class field.
A by-name type, in which the empty parameter list, (), is left out, is only
allowed for parameters. There is no such thing as a by-name variable or a
by-name field.
You should use the first function definition if you want to pass as the argument an Int by name.
Use the second definition if you want the argument to be a parameterless function returning an Int.

How to specify type when calling method?

I'm having trouble wrapping my head around how to make this method reusable:
trait T
case class A extends T
case class B extends T
def deserialize(source:Json):A = {
source.convertTo[A]
}
The .convertTo[x] method can convert into both A and B; however, at the moment this method can only produce A. How to specify what type to convert to when calling the method?
Clarification:
At the moment I could do this, but it's redundant, especially when the number of T subclasses grow:
def deserialize_A_(source:Json):A = {
source.convertTo[A]
}
def deserialize_B_(source:Json):B = {
source.convertTo[B]
}
How to merge these two methods into one, so that it would handle all subclasses of T? (Note: presume that the nested method convertTo can already handle all these subclasses.)
Because it's easier to show than explain (I presume the way I wrote it won't work):
def deserialize(source:Json, subclassToConvertTo:SubclassOfT):SubclassOfT = {
source.convertTo[subclassToConvertTo]
}
I'm not sure what library you are using, but if you look at convertTo type signature, you'll see what needs to be done. For instance, spray-json has a convertTo method that looks like this:
def convertTo[T : JsonReader]: T
The notation T : JsonReader is a context bound, a syntactic sugar for this:
def convertTo[T](implicit $ev : JsonReader[T]): T
So, basically, you need to receive a type parameter (like the T above), and an implicit value based on that type parameter, whose type depends on what convertTo on the library you are using needs. Let's say it is JsonReader, then your method becomes:
def deserialize[X : JsonReader](source:Json): X = {
source.convertTo[X]
}
Which you need to call like this, because X cannot be inferred:
deseralize[A](someSource)
If you need X to be a subtype of T, you can add that restriction like this:
def deserialize[X <: T : JsonReader](source:Json): X = {
source.convertTo[X]
}
PS: I'd really rather you didn't use things like T, A and B as types in your example, since they are common identifiers for type parameters.
def deserialize[T <: A : JsonReader](source : Json) = source.convertTo[T]
This is just a simple matter of parametrizing the method on the type of result you want. It should be covered fairly early in any book on Scala.
See for example http://twitter.github.io/scala_school/type-basics.html#parametricpoly

What is the supertype of all functions in Scala?

I know I can do instanceOf checks against Function1 or Function2 etc but is there a generic way to see if something is function or not (it can have arbitray number of args). I tried defining something like this:
type FuncType = (Any*) -> Any
But that did not work either. Basically I have some code that looks like this:
call = (name: Any, args: Any*) -> if name.isFunction then name.castAs[Function].apply(args) else name
aFunction = (name: String) => "Hello " + name
notAFunction = "Hello rick"
call(aFunction, "rick")
call(notAFunction)
There is no general supertype for all function types.
Scala has no way to abstract over the arity of a function. However, you might look into the Shapeless library, which introduces something called an HList that you can use for abstracting the arity of functions.
However, I'm thinking that's not really what you need. It sounds like you just want to do a check like "is this a function?" You might think it's weird that there's no arity-agnostic Function supertype, but you'd pretty much always need to know the arity of a function if you want to do something useful with it.
Alternatively, you might be able to do something with the curried method on the function, which will return a Function1.
No, there is no way to do this, except to go through and check each of Function1, Function2, etc. The parent of each of these traits is AnyRef, which won't help you to distinguish them from anything else. The apply method for each of these traits takes a different number of parameters, so there is no way to give them a parent that has an apply method. The closest you could probably get to what you are trying to do is:
def arbitraryFunction(function: AnyRef, args: Seq[Any]): Any = {
function match {
case f: Function1[Any, Any] => f(args(0))
case f: Function2[Any, Any, Any] => f(args(0), args(1))
// and so on
}
}
But this is insane and dangerous and will throw exceptions at runtime if the types are wrong, e.g.
arbitraryFunction((x: Int) => x * 2, List("I'm a String!"))

What is the apply function in Scala?

I never understood it from the contrived unmarshalling and verbing nouns ( an AddTwo class has an apply that adds two!) examples.
I understand that it's syntactic sugar, so (I deduced from context) it must have been designed to make some code more intuitive.
What meaning does a class with an apply function give? What is it used for, and what purposes does it make code better (unmarshalling, verbing nouns etc)?
how does it help when used in a companion object?
Mathematicians have their own little funny ways, so instead of saying "then we call function f passing it x as a parameter" as we programmers would say, they talk about "applying function f to its argument x".
In mathematics and computer science, Apply is a function that applies
functions to arguments.
Wikipedia
apply serves the purpose of closing the gap between Object-Oriented and Functional paradigms in Scala. Every function in Scala can be represented as an object. Every function also has an OO type: for instance, a function that takes an Int parameter and returns an Int will have OO type of Function1[Int,Int].
// define a function in scala
(x:Int) => x + 1
// assign an object representing the function to a variable
val f = (x:Int) => x + 1
Since everything is an object in Scala f can now be treated as a reference to Function1[Int,Int] object. For example, we can call toString method inherited from Any, that would have been impossible for a pure function, because functions don't have methods:
f.toString
Or we could define another Function1[Int,Int] object by calling compose method on f and chaining two different functions together:
val f2 = f.compose((x:Int) => x - 1)
Now if we want to actually execute the function, or as mathematician say "apply a function to its arguments" we would call the apply method on the Function1[Int,Int] object:
f2.apply(2)
Writing f.apply(args) every time you want to execute a function represented as an object is the Object-Oriented way, but would add a lot of clutter to the code without adding much additional information and it would be nice to be able to use more standard notation, such as f(args). That's where Scala compiler steps in and whenever we have a reference f to a function object and write f (args) to apply arguments to the represented function the compiler silently expands f (args) to the object method call f.apply (args).
Every function in Scala can be treated as an object and it works the other way too - every object can be treated as a function, provided it has the apply method. Such objects can be used in the function notation:
// we will be able to use this object as a function, as well as an object
object Foo {
var y = 5
def apply (x: Int) = x + y
}
Foo (1) // using Foo object in function notation
There are many usage cases when we would want to treat an object as a function. The most common scenario is a factory pattern. Instead of adding clutter to the code using a factory method we can apply object to a set of arguments to create a new instance of an associated class:
List(1,2,3) // same as List.apply(1,2,3) but less clutter, functional notation
// the way the factory method invocation would have looked
// in other languages with OO notation - needless clutter
List.instanceOf(1,2,3)
So apply method is just a handy way of closing the gap between functions and objects in Scala.
It comes from the idea that you often want to apply something to an object. The more accurate example is the one of factories. When you have a factory, you want to apply parameter to it to create an object.
Scala guys thought that, as it occurs in many situation, it could be nice to have a shortcut to call apply. Thus when you give parameters directly to an object, it's desugared as if you pass these parameters to the apply function of that object:
class MyAdder(x: Int) {
def apply(y: Int) = x + y
}
val adder = new MyAdder(2)
val result = adder(4) // equivalent to x.apply(4)
It's often use in companion object, to provide a nice factory method for a class or a trait, here is an example:
trait A {
val x: Int
def myComplexStrategy: Int
}
object A {
def apply(x: Int): A = new MyA(x)
private class MyA(val x: Int) extends A {
val myComplexStrategy = 42
}
}
From the scala standard library, you might look at how scala.collection.Seq is implemented: Seq is a trait, thus new Seq(1, 2) won't compile but thanks to companion object and apply, you can call Seq(1, 2) and the implementation is chosen by the companion object.
Here is a small example for those who want to peruse quickly
object ApplyExample01 extends App {
class Greeter1(var message: String) {
println("A greeter-1 is being instantiated with message " + message)
}
class Greeter2 {
def apply(message: String) = {
println("A greeter-2 is being instantiated with message " + message)
}
}
val g1: Greeter1 = new Greeter1("hello")
val g2: Greeter2 = new Greeter2()
g2("world")
}
output
A greeter-1 is being instantiated with message hello
A greeter-2 is being instantiated with message world
TLDR for people comming from c++
It's just overloaded operator of ( ) parentheses
So in scala:
class X {
def apply(param1: Int, param2: Int, param3: Int) : Int = {
// Do something
}
}
Is same as this in c++:
class X {
int operator()(int param1, int param2, int param3) {
// do something
}
};
1 - Treat functions as objects.
2 - The apply method is similar to __call __ in Python, which allows you to use an instance of a given class as a function.
The apply method is what turns an object into a function. The desire is to be able to use function syntax, such as:
f(args)
But Scala has both functional and object oriented syntax. One or the other needs to be the base of the language. Scala (for a variety of reasons) chooses object oriented as the base form of the language. That means that any function syntax has to be translated into object oriented syntax.
That is where apply comes in. Any object that has the apply method can be used with the syntax:
f(args)
The scala infrastructure then translates that into
f.apply(args)
f.apply(args) has correct object oriented syntax. Doing this translation would not be possible if the object had no apply method!
In short, having the apply method in an object is what allows Scala to turn the syntax: object(args) into the syntax: object.apply(args). And object.apply(args) is in the form that can then execute.
FYI, this implies that all functions in scala are objects. And it also implies that having the apply method is what makes an object a function!
See the accepted answer for more insight into just how a function is an object, and the tricks that can be played as a result.
To put it crudely,
You can just see it as custom ()operator. If a class X has an apply() method, whenever you call X() you will be calling the apply() method.

Why do I need a curried function to be able to pass function literals with short placeholder syntax?

Given this definition:
class Foo(var x: String) {}
object Helper {
def model[T](get: ⇒ T, set: T ⇒ Unit) : Model[T] = new Model[T] {
override def getObject(): T = get
override def setObject(obj: T) { set(obj) }
}
}
I try to call model like this:
val f = new Foo("initial")
val stringModel = model(f.x, f.x = _)
But that doesn't work, the compiler gives me this, complaining about the underscore:
missing parameter type for expanded function ((x$1) => f.x = x$1)
If I change the definition of model to use two parameter lists like this:
def model[T](get: ⇒ T)(set: T ⇒ Unit) // rest is unchanged
Then I can call it like this:
model(f.x)(f.x = _)
Which I find nice and concise. I don't really mind doing it like this, though it makes method overloading harder. I would like to understand, however, why the second variant works and the first one doesn't?
The second variant works because Scala refines its types parameter-block by parameter-block. If you don't specify the type of your input parameter for the function, it's possible that it would change the type T that it has inferred based on the first parameter. If you push it to a separate parameter block, Scala's already decided what T must be by the time it hits that block, so it fills in the only possible value for the function argument type.