在 Scala 中创建一个类型的新实例 [英] creating a new instance of a type in scala

查看:49
本文介绍了在 Scala 中创建一个类型的新实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 C 类定义为

If I have a class C defined as

class C[A]

有没有办法在 C 中创建 A 的新实例?类似的东西

is there any way to create a new instance of A within C? Something like

class C[A] {
  def f(): A = new A()
}

我知道,如果可能的话,您可能必须在某处指定构造函数参数,这很好.

I understand that, if this were possible, you'd probably have to specify the constructor arguments somewhere, and that's fine.

如果不可能,是否有任何设计模式可以处理您想要创建类型的新实例的情况?

If it's not possible, are there any design patterns for dealing with the sort of situation where you'd like to create a new instance of a type?

推荐答案

您可以使用类型类来抽象实例化:

You could use a type class to abstract instantiation:

trait Makeable[T] {
   def make: T
}

class C[T: Makeable] {
   def f(): T = implicitly[Makeable[T]].make
}

例如

implicit object StringIsMakeable extends Makeable[String] {
   def make: String = "a string"
}

val c = new C[String]
c.f // == "a string"

当您实例化 C 时,您需要显式或隐式地提供一个 Makeable,它将充当适当类型的工厂.当然,该工厂将负责在调用构造函数时提供任何构造函数参数.

When you instantiate C, you'll need to provide, explicitly or implicitly, a Makeable that will act as a factory of the appropriate type. That factory, of course, would be responsible for supplying any constructor arguments when it invokes the constructor.

或者,您可以使用 Manifest,但请注意,这种方法依赖于反射并且不是类型安全的:

Alternatively, you could use a Manifest, but be warned that this approach relies on reflection and is not type safe:

class C[T: Manifest] {
   def f(): T = manifest[T].erasure.newInstance.asInstanceOf[T]
}

为了完整起见,您还可以轻松扩展此方法,将部分或全部构造函数参数传递给 make 方法:

For completeness, you can also easily extend this approach to pass some or all of the constructor parameters in to the make method:

trait Makeable[Args, T] { def make(a: Args): T }

class C[Args, T](implicit e: Makeable[Args, T]) {
   def f(a: Args): T = e.make(a)
}

// some examples
case class Person(firstName: String, lastName: String)

implicit val personFactory1 = new Makeable[(String, String), Person] {
   def make(a: (String, String)): Person = Person(a._1, a._2)
}
implicit val personFactory2 = new Makeable[String, Person] {
   def make(a: String): Person = Person(a, "Smith")
}

val c1 = new C[String, Person]
c1.f("Joe") // returns Person("Joe", "Smith")

val c2 = new C[(String, String), Person]
c2.f("John", "Smith") // returns Person("John", "Smith")

这篇关于在 Scala 中创建一个类型的新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆