在Scala中重命名classOf

时间:2011-06-09 09:08:30

标签: scala dsl

我正在使用ScalaTest的客户可读DSL。目前我可以写

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

但是这会更好地阅读

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

有没有办法

def the[T] = 

返回classOf[T]

2 个答案:

答案 0 :(得分:17)

你可以试试这个:

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

符号[T: ClassManifest] context bound ,相当于:

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

Manifest[T]ClassManifest[T]的隐含值由编译器自动填充(如果它可以重新传递传递给方法的类型参数)并为您提供有关T的运行时信息:ClassManifest只将其删除为Class[_]Manifest还可以告知您T本身的可能参数化(例如,如果T为{ {1}},然后您也可以了解Option[String]部分。

答案 1 :(得分:3)

您可能想要做的只是在导入时重命名方法(在Predef对象中定义):

import Predef.{ classOf => the, _ }

请注意,如果您像这样重命名,classOf将不再起作用。如果您仍然需要它,也请添加此导入:

import Predef.classOf;

有关更多重命名的善意,请参阅: