Skip to content

Instantly share code, notes, and snippets.

@velvia
Created September 30, 2015 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save velvia/4e923bf6eac6b4e8e7a0 to your computer and use it in GitHub Desktop.
Save velvia/4e923bf6eac6b4e8e7a0 to your computer and use it in GitHub Desktop.
Calling a function by type parameter in Scala

Let's say you have a Scala function which takes type parameter:

  def myFunc[K]: T

Let's say I have several functions like that. Right now, if K could be one of several different values, I'd need some code like the following:

  kType match {
    case KIsInt =>  myFunc[Int]
    case KIsLong => myFunc[Long]
  }

I'd like a generic wrapper function that can switch on kType and call different functions. Is this possible? Something like this.

  def kFuncCall[T](kType: KType)(callFunc: [K] => T): T = {
    kType match {
      case KIsLong    => callFunc[Long]
      case KIsInt     => callFunc[Int]
    }
@velvia
Copy link
Author

velvia commented Oct 14, 2015

@gclaramunt thanks. I tried looking in Shapeless but didn't find anything that would help. Maybe Scalaz. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment