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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you - I have tried it, and it works! I have no idea what it does though - I've gone from being a big Java shark to a Scala minnow ;-)
@Duncan I've added a short explanation about context bounds and manifests.
You're a gent - yet more Scala'y goodness to digest. I haven't been this keen since I bought Coplien's book on C++
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:

5 Comments

Nice, but this depends on clients of your library writing the right imports.
Well you'd have to import your own the implementation too, wouldn't you?
Yes, with something easy like import mylib._, without the need for an extra import Predef.{ classOf => the, _ }.
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'
@x3ro Good point about the automatic package import. I asked a similar question here, and for lack of answers I've concluded that such a thing is not possible at the time (2.9).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.