开发者

Renaming classOf in Scala

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[AdminHome开发者_如何学CPage])
    then(the[SignInPage], "is displayed")

Is there any way to

def the[T] = 

to return classOf[T] ?


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜