Scala 2.12,实例化类型参数?

时间:2017-07-20 20:52:57

标签: scala types

已经有关于我想做什么的信息,但还没有想出来。我想实例化一个作为上下文绑定传递的类型的元素,如下所示:

case class Person(name: String)
case class Dog(name: String)

abstract case class Message[T](result: Map[String, T])

// using Person as a type here
case class PersonMessage(val result: Map[String, Person]) extends Message[Person](result)

// using Dog as a type here
case class DogMessage(val result: Map[String, Dog]) extends Message[Dog](result)

我当然可以实例化这些对象:

val pm: PersonMessage = PersonMessage(Map("joe" -> Person("joe")))
val dm: DogMessage = DogMessage(Map("blacky" -> Dog("blacky")))

但是我可以在通用函数中执行此操作吗?

// should return a PersonMessage or a DogMessage
def myfunction[T, U <: Message[T]](customName: String): U = {
  U(Map(customName -> T(customName)))
}

val p: PersonMessage = myFunction[Person, PersonMessage]("joe")
val d: DogMessage = myFunction[Dog, DogMessage]("blacky")

此语法不起作用,但还有其他方法可以实现吗?谢谢你的提示。

1 个答案:

答案 0 :(得分:1)

问题在于,仅通过定义类型TU <: Message[T],您无法保证构造函数采用何种类型的参数。为什么有人不能将T设置为某种没有单字符串参数构造函数的类型来调用它?相反,您可以使用适当的类型显式传入构造函数。以下是我将如何处理它:

def myFunction[T, U <: Message[T]](customName: String, mkT: String => T, mkU: Map[String, T] => U): U = {
  mkU(Map(customName -> mkT(customName)))
}

val p: PersonMessage = myFunction("joe", Person, PersonMessage)
val d: DogMessage = myFunction("blacky", Dog, DogMessage)