Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming classOf in Scala

Tags:

scala

dsl

I'm working on a customer-readable DSL for ScalaTest. At the moment I can write

feature("Admin Login") {
  scenario("Correct username and password") {
    given("user visits", classOf[AdminHomePage])
    then(classOf[SignInPage], "is displayed")

but this would read a lot better as

feature("Admin Login") {
  scenario("Correct username and password") {
    given("user visits", the[AdminHomePage])
    then(the[SignInPage], "is displayed")

Is there any way to

def the[T] = 

to return classOf[T] ?

like image 726
Duncan McGregor Avatar asked Jun 09 '11 09:06

Duncan McGregor


2 Answers

You could try this:

def the[T: ClassManifest]: Class[T] =
  classManifest[T].erasure.asInstanceOf[Class[T]]

The notation [T: ClassManifest] is a context bound and is equivalent to:

def the[T](implicit classManifest: ClassManifest[T])

Implicit values for Manifest[T] and ClassManifest[T] are automatically filled in by the compiler (if it can reify the type parameter passed to the method) and give you run-time information about T: ClassManifest gives just its erasure as a Class[_], and Manifest additionally can inform you about a possible parametrization of T itself (e.g., if T is Option[String], then you can learn about the String part, too).

like image 160
Jean-Philippe Pellet Avatar answered Nov 14 '22 16:11

Jean-Philippe Pellet


What you probably want to do is just rename the method (which is defined in the Predef object) on import:

import Predef.{ classOf => the, _ }

Note that classOf won't work anymore if you rename it like this. If you still need it, also add this import:

import Predef.classOf;

For more renaming goodness see also:

  • How do I exclude/rename some classes from import in Scala?
  • Unimporting in Scala
  • what's wrong with renaming imported static functions?
  • Scalada (beware, it its all pink o.o)
like image 3
fresskoma Avatar answered Nov 14 '22 16:11

fresskoma