scala - 获取 FunctionX 参数和输出类型
问题描述
我正在努力获取 Scala 中已定义函数的参数类型。例如Funcion1[T1, T2]
.
由于 Java 将消除类型检查(编译器警告:)is unchecked since it is eliminated by erasure
,我想找到一种方法来match
使用它们的类型。
目标是能够具有与以下相同的功能:
val fnInput = {x: Map[String, Double] => x}
fnInput match {
case f: Function1[Map[String, Double], Map[String, Double]] => ???
case f: Function1[T1, T2] => ???
case f: Function2[T1, T2, T3] => ???
}
但是,检查参数类型。
更新:到目前为止,我的解决方案将使用以下工具
import scala.reflect.runtime.universe._
def getType[T: TypeTag](obj: T) = typeOf[T]
val t = getType({x: Map[String, Any] => x})
// check first argument
typeOf[Map[String, Int]] <:< t.typeArgs(0)
// check return of Function1
typeOf[Map[String, Int]] <:< t.typeArgs(1)
// t.typeArgs.length will return the number of arguments +1
您认为这是一个好方法吗?
解决方案
推荐阅读
- google-sheets - Google Sheets:基于 Master Sheet 自动在多个工作表中添加行
- r - 在至少一个 data.frame 中输出包含 NA 的行名
- python - 虽然循环!= 没有按预期工作?
- ruby-on-rails - 部署到 Heroku 时获取 KeyError: key not found: secret_key_base
- machine-learning - 如何标准化 db 规模的频谱图?
- java - 使用 Elastic Search 6.1.1 配置 Spring-Boot-1.4.3
- reactjs - 使用 Nginx 刷新页面显示 404 错误
- azure - 在 powershell 中使用 get-Credentials 创建 azure secret
- java - 在 Windows 10 上双击 Eclipse 安装程序可执行文件 (eclipse-inst-jre-win64.exe) 后没有任何反应
- node.js - 处理快递申请中未处理的承诺拒绝