Scala 传递类型参数的力
出于某种原因,我有Scala 传递类型参数的力,scala,types,type-conversion,type-parameter,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 anot
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的没有指定编译时要中断的类型,而没有指定要工作的类型。不能强制显式提供类型参数。 也许你可以把它变成一个正常的论点,如果你真的想要这种行为
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")
不要认为这是可能的。你无法阻止
t
被推断为Int
,因此这两者基本上是完全相同的东西……“出于某种原因”。为什么?@Paul一个大型+复杂的现有系统正在从推断的类型中制造问题。这个解决方案会更快、更干净,但听起来我会更深入地寻找另一个解决方案:)