Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a parameter type - [T <: AnyRef]

Looking at the method signature of 'intercept' within scala test :

 def intercept[T <: AnyRef](f: => Any)(implicit manifest: Manifest[T]): T = {

I dont know how [T <: AnyRef] is used ? This looks like a parameter type but why is it contained within angled brackets - [] ?

Here is the complete method :

  def intercept[T <: AnyRef](f: => Any)(implicit manifest: Manifest[T]): T = {
    val clazz = manifest.erasure.asInstanceOf[Class[T]]
    val caught = try {
      f
      None
    }
    catch {
      case u: Throwable => {
        if (!clazz.isAssignableFrom(u.getClass)) {
          val s = Resources("wrongException", clazz.getName, u.getClass.getName)
          throw newAssertionFailedException(Some(s), Some(u), 4)
        }
        else {
          Some(u)
        }
      }
    }
    caught match {
      case None =>
        val message = Resources("exceptionExpected", clazz.getName)
        throw newAssertionFailedException(Some(message), None, 4)
      case Some(e) => e.asInstanceOf[T] // I know this cast will succeed, becuase iSAssignableFrom succeeded above
    }
  }
like image 639
blue-sky Avatar asked Jun 19 '26 10:06

blue-sky


1 Answers

This language construct is called type parameterization, and you can read more about it here:

http://www.artima.com/pins1ed/type-parameterization.html

In this case a method can also declare type parameter. If you already have some Java background, then here is very similar Java equivalent:

public <T extends Object> T intercept(Runnable f) {
  // ...
}
like image 137
tenshi Avatar answered Jun 21 '26 23:06

tenshi