[英]Scala Function1 Generic parameter and return type
Lets say I want to store a Map[String, Function1]
where the parameter and return type of the Function1 can vary. 可以说我想存储一个
Map[String, Function1]
,其中Map[String, Function1]
的参数和返回类型可以变化。 How would I go about storing a Function1[String, String]
and Function1[Int, Int]
in the same Map. 我将如何在同一个Map中存储
Function1[String, String]
和Function1[Int, Int]
。
I've tried Function1[AnyRef, AnyRef]
but Function1[String, String]
isn't a Function1[AnyRef, AnyRef]
so it fails to compile. 我已经尝试过
Function1[AnyRef, AnyRef]
但Function1[String, String]
不是Function1[AnyRef, AnyRef]
因此无法编译。
If you have only two possible value types, you can wrap values in Either : 如果只有两种可能的值类型,则可以将值包装在Either中 :
val m = Map[String, Either[Int => Int, String => String]]()
If you want to store more than two different types, create your own wrapper, or use something like Coproduct from shapeless . 如果要存储两种以上的不同类型,请创建自己的包装器,或使用诸如shapeless的Coproduct之类的东西。
Does this look like what you're after? 这看起来像您所追求的吗?
scala> val m = Map[String, Function1[_,_]]()
m: scala.collection.immutable.Map[String,Function1[_, _]] = Map()
scala> val f1 = (i:Int) => i*3
f1: Int => Int = <function1>
scala> val f2 = (b: Boolean) => if (b) "YES" else "NO"
f2: Boolean => String = <function1>
scala> m + ("xcx" -> f2) + ("rtr" -> f1)
res59: scala.collection.immutable.Map[String,Function1[_, _]] = Map(xcx -> <function1>, rtr -> <function1>)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.