简体   繁体   English

隐式参数vs TypeTag何时使用以及为什么

[英]implicit paramters vs TypeTag when to use and why

Scala suffers type erasure , but it also introduces TypeTag to overcome type erasure problem. Scala遭受类型擦除 ,但是它也引入TypeTag来克服类型擦除问题。

Sometimes we can use implicit parameters (or even value paramters are enough) to solve the same problem that we countered. 有时我们可以使用隐式参数 (甚至值参数就足够了)来解决我们遇到的相同问题。

For exammple: 例如:

// implicit paramters
def getKindName[T](implicit x: T): String = {
      x match {
        case _: People => "Mammals"
        case _: Sparrow => "Birds"
        case _: Shark => "Fishes"
        case _: Crocodile => "Reptiles"
        case _ => ???
      }
}

// TypeTag
def getKindName[T: TypeTag]: String = {
    typeOf[T] match {
      case t if t =:= typeOf[People] => "Mammals"
      case t if t =:= typeOf[Sparrow] => "Birds"
      case t if t =:= typeOf[Shark] => "Fishes"
      case t if t =:= typeOf[Crocodile] => "Reptiles"
      case _ => ???
    }
}

So my question are: 所以我的问题是:

  • why and when use Type Tag and implicit paramters ? 为什么以及何时使用类型标记和隐式参数?
  • what are the differences of perfomance between Type Tag and implicit paramters? 类型标签和隐式参数之间的性能有何区别?

If you could give me a link of doc in scala to prove your opinion, it is perfect. 如果您可以在scala中给我一个doc链接来证明您的观点,那是完美的。 Thank you in advance. 先感谢您。

  1. TypeTag s are nearly always used as implicit parameters. TypeTag s的几乎总是作为隐含参数。 If you aren't aware, getKindName[T: TypeTag] means getKindName[T](implicit tag: TypeTag[T]) . 如果您不知道, getKindName[T: TypeTag]意思是getKindName[T](implicit tag: TypeTag[T]) The exception would be when you store a TypeTag which you got as an implicit parameter somewhere. 例外是当您将TypeTag作为隐式参数存储在某处时。 So "implicit parameters vs TypeTag " doesn't make sense to begin with. 因此,“隐式参数 TypeTag ”一开始就没有意义。

  2. The two snippets do not behave at all similarly, so they can't be solving the same problem, whatever that problem is. 这两个代码片段的行为根本不一样,因此无论该问题是什么,它们都无法解决相同的问题。 Eg you can define 例如,您可以定义

     implicit val x: Animal = new People getKindName1[Sparrow] // returns "Mammals" 

    or without any extra implicits being defined, getKindName1[Sparrow] will not compile at all (and it isn't clear why you would have eg an implicit Sparrow in the first place). 或没有定义任何额外的隐式, getKindName1[Sparrow]根本不会编译(并且不清楚为什么首先要有一个隐式Sparrow )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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