Skip to content

Instantly share code, notes, and snippets.

@janhicken
Last active November 25, 2017 16:07
Show Gist options
  • Save janhicken/3f30b227df475a75c58c571ed19f61d7 to your computer and use it in GitHub Desktop.
Save janhicken/3f30b227df475a75c58c571ed19f61d7 to your computer and use it in GitHub Desktop.
Extract EMF Resource (type-)safely with Scala pattern matching
import java.io.IOException
import org.eclipse.emf.ecore.EObject
import org.eclipse.emf.ecore.resource.Resource
import scala.collection.JavaConverters._
import scala.reflect.ClassTag
class TypesafeResourceExtractor[T <: EObject : ClassTag] {
def extractResource(resource: Resource): T = {
resource.getContents.asScala.headOption match {
case None => throw new IOException("resource is empty")
case Some(t: T) => t
case Some(other) => throw new IOException(s"resource contains the wrong type: ${other.eClass().getName}")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment