简体   繁体   English

Scala TypeTag缺少类名

[英]Scala TypeTag missing class name

I'm trying to get some information using Scala's reflect library : 我正在尝试使用Scala的反射库获取一些信息:

abstract class Model

class Person extends Model

class Car extends Model

abstract class AbstractDao[T <: Model]

object PersonDao extends AbstractDao[Person]

object CarDao extends AbstractDao[Car]

object DataLoader {

  val daos = Seq(PersonDao, CarDao)
  val modelToString = daos.map(genericImportEntities(_))

  val modelToString2 = Seq(genericImportEntities(PersonDao), genericImportEntities(CarDao))

  private def genericImportEntities[T <: Model](dao: AbstractDao[T])
                                               (implicit
                                                t2: TypeTag[T]
                                               ): String = {

    t2.tpe.toString
  }
}

If I call modelToString, the output is List(_1, _1) 如果我调用modelToString,则输出为List(_1,_1)

With modelToString2, it is List(Person, Car) 与modelToString2一起,它是List(Person,Car)

Any idea how can I make modelToString work? 任何想法如何使modelToString工作?

The issue is that type of daos is Seq[AbstractDao[_]] . 问题是daos类型是Seq[AbstractDao[_]] So when calling daos.map(genericImportEntities(_)) , T is an unknown type which the compiler calls _1 . 因此,当调用daos.map(genericImportEntities(_))T是编译器调用_1的未知类型。 Generally, TypeTag s are only useful when you know the static types at the point where the compiler should insert them, and in this case you don't. 通常, TypeTag仅在知道静态类型时才有用,编译器应在其中插入静态类型,而在这种情况下则不需要。

The easiest way to fix this would be to move TypeTag into AbstractDao : 解决此问题的最简单方法是将TypeTag移到AbstractDao

abstract class AbstractDao[T <: Model](implicit val tag: TypeTag[T])

private def genericImportEntities[T <: Model](dao: AbstractDao[T]) = 
  dao.tag.tpe.toString

Then the compiler inserts the tags at definition of PersonDao and CarDao and they can be used later in genericImportEntities . 然后,编译器在PersonDaoCarDao定义处插入标签,以后可以在genericImportEntities使用它们。

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

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