Cory Klein Cory Klein - 3 months ago 10
Scala Question

Given a Type, create an Option Type that contains it

Given a

Type
named
inner
, I would like to create a new
Type
that represents an
Option
containing a type of the same type as
inner
.

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

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

import scala.reflect.runtime.universe._

def createOptionType(inner: Type): Type = 
  appliedType(typeOf[Option[_]], inner)