7

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] ?

Duncan McGregor
  • 17,665
  • 12
  • 64
  • 118

2 Answers2

17

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).

Community
  • 1
  • 1
Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234
3

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:

Community
  • 1
  • 1
fresskoma
  • 25,481
  • 10
  • 85
  • 128
  • Nice, but this depends on clients of your library writing the right imports. – Jean-Philippe Pellet Jun 09 '11 at 13:34
  • Well you'd have to import your own `the` implementation too, wouldn't you? – fresskoma Jun 09 '11 at 13:44
  • Yes, with something easy like `import mylib._`, without the need for an extra `import Predef.{ classOf => the, _ }`. – Jean-Philippe Pellet Jun 09 '11 at 13:47
  • 2
    yes but there is a big difference between telling your users 'just import xxx._' and 'import xxx._ and Predef.{ classOf => the, _ } and if you still need it Predef.classOf' – Jens Schauder Jun 09 '11 at 13:48
  • @x3ro Good point about the automatic package import. I asked a similar question [here](http://stackoverflow.com/questions/5744768/can-i-import-from-multiple-packages-all-at-once-in-scala), and for lack of answers I've concluded that such a thing is not possible at the time (2.9). – Jean-Philippe Pellet Jun 09 '11 at 14:35