简体   繁体   中英

Scala methods with generic parameter type

I have been working with Scala for close to a year, but every now and then I come across a piece of code that I don't really understand. This time it is this one. I tried looking into documents on "scala methods with generic parameter type", but I am still confused.

def defaultCall[T](featureName : String) (block : => Option[T])(implicit name: String, list:Seq[String]) : Option[T] = 
{
   val value = block match {
     case Some(n) => n match {
        case i : Integer => /*-------Call another method----*/
        case s : String => /*--------Call another method----*/
      }
      case _ => None
 }

The method is called using the code shown below :

 var exValue = Some(10)
 val intialization = defaultCall[Integer]("StringName"){exValue}

What I don't understand in the above described code is the "case" statement in the defaultCall method.

I see that when the exValue has a value and is not empty, the code works as expected. But in case I change the exValue to None, then my code goes into the "case _ = None" condition. I don't understand why this happens since the match done here is against the "variable" which would be either an Integer or a String.

What happens here is that when you pass a None it will match on the second case, which "catches" everything that is not an instance of a Some[T]:

block match {
  case Some(n) => // Will match when you pass an instance of Some[T]
  case _       => // Will match on any other case
}

Note that None and Some are two different classes that inherit from Option.

Also, the variable match is only done if the first match succeeds, otherwise not. To achieve the type checking in the first match you could do:

block match {
  case Some(n: Int)    => // do stuff
  case Some(n: String) => // do stuff
  case _               => // Will match on any other case
}

Hope that helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM