简体   繁体   English

Scala 2.12,实例化类型参数?

[英]Scala 2.12, instantiate type parameter?

There is already information about what I want to do, but couldn't figure it out yet. 已经有关于我想做什么的信息,但是还不能弄清楚。 I would like to instantiate an element of a type passed as a context bound, something like this: 我想实例化作为上下文绑定传递的类型的元素,如下所示:

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)

I can certainly instantiate these objects: 我当然可以实例化这些对象:

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

but could I do this in a generic function? 但是我可以在通用函数中执行此操作吗?

// 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")

This syntax doesn't work, but are there other ways to achieve this? 该语法不起作用,但是还有其他方法可以实现此目的吗? Thanks for any hint. 感谢您的任何提示。

The issue is that by just defining the type T or U <: Message[T] you have no guarantees about what kind of arguments the constructors take. 问题是,仅定义TU <: Message[T]类型,就不能保证构造函数采用哪种参数。 Why couldn't someone call it with T set to some type that doesn't have a one-string-argument constructor? 为什么没有人用T设置为没有一串参数构造函数的类型来调用它? Instead you can explicitly pass in constructors with appropriate types. 相反,您可以使用适当的类型显式传递构造函数。 Here's how I would handle it: 这是我的处理方式:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM