强制传递类型参数

时间:2015-01-19 20:19:35

标签: scala types type-conversion type-parameter

出于某种原因,我有

val stuff: Map[String, Any] = Map[String, Any](
  ("a", 1),
  ("b", "one"),
  ("c", false)
)

def getThing[T](key: String): T = {
  stuff.get(key).get.asInstanceOf[T]
}

val a: Int = getThing("a") // I want this to break on compile
val anotherA: Int = getThing[Int]("a") // I want this to work as normal

我希望get的没有指定要在编译时中断的类型,以及那些执行指定工作的类型。

1 个答案:

答案 0 :(得分:1)

您无法强制显式提供类型参数。 如果你真的想要这种行为,也许你可以把它变成一个正常的论点......

case class Type[T]

def getThing[T](t: Type[T])(key: String): T =
  stuff.get(key).get.asInstanceOf[T]

val a = getThing(Type[Int])("a")
相关问题