0

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?

1
  • Like Future[A] or just some generic type A? Commented Apr 17, 2015 at 14:37

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.