Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 传递类型参数的力_Scala_Types_Type Conversion_Type Parameter - Fatal编程技术网

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一个大型+复杂的现有系统正在从推断的类型中制造问题。这个解决方案会更快、更干净,但听起来我会更深入地寻找另一个解决方案:)