vendredi 3 février 2017

Scala: Default value for function parameter with generics

I am having trouble for setting a default value for a function parameter when the types are generics.

My function signature looks like:

  def doStuff[ K, T ]( result: Future[ Seq[ T ] ] )
                     ( transform: T => Option[ K ] ): Future[ Either[ String, Option[ K ] ] ] = {
  }

And I am aware that I cat set a default value to a function parameter like:

  def doStuff(a: Int)
             (f: Int => Option[Int] = k => Option(k)): Future[ Either[ String, Option[ Int ] ] ] = {
  }

However I can't combine these generic types with a default function value

  def doStuff[ K, T ]( result: Future[ Seq[ T ] ] )
                     ( transform: T => Option[ K ] = k => Option(k)): Future[ Either[ String, Option[ K ] ] ] = {
  }

with an obvious error message: Option[T] does not conform expected Option[K]

my last resort is to pass class tag in for K and T and change the default parameter from k => Option(k) to

def doStuff[ K: ClassTag, T ]( result: Future[ Seq[ T ] ] )
                               ( transform: T => Option[ K ] = {
                                 case m: K => Option( m )
                                 case _ => None
                               } ): Future[ Either[ String, Option[ K ] ] ] = {
  }

but this approach will force me to pass in my generic parameters on function call.

Can anyone see any other approach?





Aucun commentaire:

Enregistrer un commentaire