Ben Dilts
Ben Dilts

Reputation: 10745

Scala: return default value of a parameterized type

Consider the following function in Scala:

def wrapMyFunction[A](foo: =>A):A = {
    try {
        foo
    }
    catch { case e => 
        //Return whatever the "empty" or "default" instance of type A would be,
        //such as 0, "", None, List(), etc.
    }
}

Given the type parameter A, how do I get the "empty" or "default" value of the type A? Is it even possible?

Upvotes: 2

Views: 776

Answers (2)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297275

Well, technically, it is not possible, for the simple reason that there isn't such a thing as a "default" value.

The examples you give are all monoidal zeros, so, with Scalaz, you could write this:

def wrapMyFunction[A : Zero](foo: =>A):A = {
  ...
  catch { case e: Exception => // do not catch all throwables!
    implicitly[Zero[A]].zero
  }
}

Another alternative would be to instantiate a value. You can use a ClassManifest or a ClassTag (Scala 2.10.0) for that. For example:

def wrapMyFunction[A : scala.reflect.ClassTag](foo: => A): A = {
  ...
  catch { case e: Exception =>
    implicitly[scala.reflect.ClassTag[A]].runtimeClass.newInstance.asInstanceOf[A]
  }
}

That, however, depends on the existence of a parameterless constructor. Using a ClassManifest is pretty much the same.

Upvotes: 6

Kristian Domagala
Kristian Domagala

Reputation: 3696

As Daniel said, it's not generally possible without some type restriction on A. What about changing the method to take a default value, either explicitly or implicitly:

def wrapMyFunction[A](foo: =>A, fallback: =>A):A = ...

or

def wrapMyFunction[A](foo: =>A)(implicit fallback:A):A = ...

Upvotes: 0

Related Questions