开发者

How to get the actual type of a generic type?

开发者 https://www.devze.com 2023-02-18 08:27 出处:网络
There is a class with generic type: class Action[T] Create some instances of it, put in a list: val list = List(new Action[String], new Action[Int])

There is a class with generic type:

class Action[T]

Create some instances of it, put in a list:

val list = List(new Action[String], new Action[Int])

Iterate it, and how to get the actual type of the instances?

list foreach { action =>
     // how do I开发者_如何学JAVA know the action is for a String or an Int?
}


Scala erases generic type parameters at compilation, so you would need to have some additional evidence in you object other than what traditional reflection provides. See:

How do I get around type erasure on Scala? Or, why can't I get the type parameter of my collections?

This questions seems to imply there might be some magic to apply in some circumstances:

Accounting for type parameters in a Scala generic class 'equals' method... are manifests the only way?

0

精彩评论

暂无评论...
验证码 换一张
取 消