何时使用随播对象工厂与new关键字 [英] When to use companion object factory versus the new keyword

查看:74
本文介绍了何时使用随播对象工厂与new关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala标准库中的许多类都将其伴随对象的 apply()用作工厂。当链接诸如 List(List(1))之类的调用时,这通常很方便。另一方面,仍然可以直接使用 new new HashMap [Int,Int]() )。

Many classes in the Scala standard library use apply() of their companion object as factory. This is often convenient when chaining calls like List(List(1)). On the other hand, it's still possible to create objects directly with new (new HashMap[Int, Int]()).

这是标准库。现在,在我自己的代码中,哪种方法更好使用:伴侣工厂或使用 new 创建对象?

That's standard library. Now, in my own code, which approach is better to use: companion factory or creating objects with new?

关于何时创建伴侣对象工厂以及何时使用 new 关键字有约定吗?

Is there any convention on when to create companion object factory and when to do with the new keyword?

使用一个相对于另一个有什么优势?

What are the advantages of using one over the other?

推荐答案

在大多数情况下,我使用伴随对象的 apply 方法,因为代码看起来不太混乱。但是,使用静态工厂至少有一个好处。考虑一个没有想象力的类型 MyInt ,它只是包装了一个 Int

In most cases I use the companion object's apply method, because the code looks less cluttered. However, there is at least one benefit of using a static factory. Consider the unimaginative type MyInt which just wraps an Int:

class MyInt(val i: Int) 

我可以获取 MyInt 的实例,该实例调用构造函数,该实例将在每次调用构造函数时实例化一个新对象。如果我的程序非常依赖 MyInt ,则会导致创建许多实例。假设我使用的大多数 MyInt -1 0 1 ,因为 MyInt 是不可变的,所以我可以重用相同的实例:

I can obtain instances of MyInt calling the constructor which will instantiate a new object each time the constructor is called. If my program relies heavy on MyInt this results in a lot of instances created. Assuming most of the MyInt I use are -1, 0, and 1, since MyInt is immutable I can reuse the same instances:

class MyInt(val i: Int) 

object MyInt {
  val one = new MyInt(1)
  val zero = new MyInt(0)
  val minusOne = new MyInt(-1)

  def apply(i: Int) = i match {
    case -1 => minusOne
    case 0 => zero
    case 1 => one
    case _ => new MyInt(i)
  }
}

因此至少对于不可变值使用静态工厂而不是调用构造函数可能具有技术优势。这意味着,如果要在代码中表示已创建新实例,请使用 new 关键字。就个人而言,我在创建对象时使用 new -关键字,在创建值时使用 apply -方法不知道是否有正式公约。

So at least for immutable values there can be a technical advantage of using the static factory over calling the constructor. As an implication, if you want to express in code that a new instance is created, then use the new keyword. Personally, I use the new-keyword when creating objects, and the apply-method when creating values, though I don't know if there is an official convention.

这篇关于何时使用随播对象工厂与new关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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