Cory Klein Cory Klein - 1 year ago 72
Scala Question

Given a Type, create an Option Type that contains it

Given a

, I would like to create a new
that represents an
containing a type of the same type as

For example, the signature of a method that would do this may look something like:

def createOptionType(inner: Type): Type = {
typeOf[Option[inner]] // this line is pseudocode

This answer helps partially, but makes use of a generic method, whereas in this case I have a concrete type passed in, making generics unuseable.

Answer Source

You can use scala.reflect.runtime.universe.appliedType for that:

import scala.reflect.runtime.universe._

def createOptionType(inner: Type): Type = 
  appliedType(typeOf[Option[_]], inner)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download