StopKran
StopKran

Reputation: 395

Scala generic methods that take functions

I have a method:

private def foo(f: => Future[Any]): Future[Any] = {
    //code, code, code
    //function return same result as function that taken
}

This works well but I need to use this in different part of my project with different types, and there are some restrictions. If I need to call some method of a type that I use, then it is not available, without casting.

For example:

if(foo("abacaba").containsSlice("dabacaba")){...}

if(foo(15) > 55){...}

Is there way to create generic function, to handle all these cases?

Upvotes: 0

Views: 75

Answers (2)

Maxim
Maxim

Reputation: 7348

You already have it defined in Scala's library as scala.Function0 You actually have also traits that define functions that get parameters as Function1 - Function22.

This is the source code for Function0 -

trait Function0[@specialized(Specializable.Primitives) +R] extends AnyRef { self =>
  /** Apply the body of this function to the arguments.
   *  @return   the result of function application.
   */
  def apply(): R

  override def toString() = "<function0>"
}

If you want to get Future as a param you can write very similar Trait for Future.

Upvotes: 0

Claudio
Claudio

Reputation: 1858

You need to specify that the return type of the function you are getting (that might be anything) is the same type your function is returning.

private def foo[T](f: => Future[T]): Future[T] = {
    //code, code, code
    //function return same result as function that taken
}

I don't think it is really necessary to say [T <: Any] since everything is of type Any

Upvotes: 3

Related Questions