首页 > 解决方案 > 获取 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

您认为这是一个好方法吗?

标签: scalascala-reflect

解决方案


推荐阅读