Edamame
Edamame

Reputation: 25366

Scala: having a function with generic return type

I have the following code which I am hoping to have a generic return type for my function:

object myUtility {

  def myFunction(input1:String, input2:String, returnType: T): T = {

  :
  :
}

What should be the right syntax and what should I import in order to achieve this? Thank you very much!

Upvotes: 4

Views: 4545

Answers (2)

turbo_laser
turbo_laser

Reputation: 261

In order to have a return value type that swaps out like that you need to use a type parameter. Something like...

  def fxn[T](x : T) : T = {
    x
  }

Upvotes: 1

Jesper
Jesper

Reputation: 206786

You are not declaring that T is a type parameter on the method. You need to do that by adding [T] before the value parameter list:

def myFunction[T](input1:String, input2:String, returnType: T): T = ...

(Also, what's the parameter returnType for? You don't need that if your only intention with that was to declare the return type).

Upvotes: 5

Related Questions