Scala如何无需知晓输出类型召唤适配输入类型的多态函数
结论
该需求在 Scala 2 中无法实现,必须升级到 Scala 3 才能完成。
原因说明
Scala 2 的类型推导采用从左到右的流式正向推导逻辑,仅支持通过已传入的实参值类型推导泛型参数,不支持基于上下文预期类型的反向推导,且类型参数的推导优先级远低于值参数,这就是你自定义的summon方法无法生效的核心原因。
而 Scala 3 大幅优化了类型推导能力,支持预期类型驱动的反向推导,正好匹配你的需求场景。
Scala 3 实现示例
基础版本(基于原生Function2)
// 原方法定义保持不变 def commutative[A, B]: ((A, B) => (B, A)) = (a, b) => (b, a) // 你的findApplicable方法调整为泛型约束入参类型 def findApplicable[T](fn: T => Any): T => Any = fn // 调用时会自动推导commutative的A=Int、B=String val res = findApplicable[(Int, String) => (String, Int)](commutative)
适配自定义SummonedFn版本
trait SummonedFn[-I, +O] extends (I => O): final def summon[II <: I]: this.type = this // 用自定义特质定义commutative def commutative[A, B]: SummonedFn[(A, B), (B, A)] = (in: (A,B)) => (in._2, in._1) // 两种调用方式都可正常推导 // 方式1:直接调用summon val b = commutative.summon[(Int, String)] // 方式2:通过findApplicable调用 def findApplicable[T](fn: SummonedFn[T, _]): SummonedFn[T, _] = fn val res2 = findApplicable[(Int, String)](commutative)
内容的提问来源于stack exchange,提问作者tribbloid
相关产品推荐
相关产品推荐

