Scala元组的构造函数解包 [英] Scala tuple unpacking for constructors

查看:264
本文介绍了Scala元组的构造函数解包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有两个参数的Scala类,以及另一个一个参数构造函数. 对于一个参数构造函数,我调用一种方法来获取两个元素的元组,并尝试将元组用作需要两个参数的构造函数的参数.这是一个例子:

I have a Scala class with two parameters, and another one parameter constructor. For the one parameter constructor, I call a method to get a tuple of two elements and tried to use the tuple for the parameter of the constuctor that requires two parametes. This is an example:

def vals(v:Int) = {
    // computation
    (v,v) // returns two element tuple
}

class A(a:Int, b:Int) {
    def this(v:Int) = {
        this(vals(v))
    }
}

object Main extends App {
    val a = new A(10)
}

但是,我收到类型不匹配错误. 我在 scala tuple unpacking 中找到了一种解决方案,该解决方案可用于函数调用,但不适用于构造函数.

However, I get type mismatch error. I found a solution in scala tuple unpacking that works with function invocation, but not with constructor.

def foo(x: Int, y: Int) = x * y
def getParams = {
    (1,2)  //where a & b are Int
}

object Main extends App {
    println((foo _).tupled(getParams))
    println(Function.tupled(foo _)(getParams))
}

如何解决此问题?

推荐答案

为该类创建一个伴随对象,并向其添加几个"factory"("apply")方法,然后放弃额外的构造方法以使用工厂方法.如果需要,您还可以在其中包含vals方法,以将内容保持在一起(尽管也可以将其定义在其他位置,如果这样对您更好).然后,您将得到如下所示的内容:

Create a companion object for the class and add a couple of "factory" ("apply") methods to it, then ditch the extra constructor in favour of the factory methods. You can also include the vals method there to keep things together, if you want (although you can keep it defined elsewhere, too, if that works better for you). Then you end up with something like the following:

class A(val a:Int, val b:Int)

object A {

  def apply(pair: (Int, Int)): A = new A(pair._1, pair._2)

  def apply(v: Int): A = A(vals(v))

  def vals(v:Int) = {
    // computation
    (v,v) // returns two element tuple
  }
}

并使用以下命令创建您的A:

And create your A with:

scala> val a = A(10)
a: A = A@36d6ec03

scala> a.a
res6: Int = 10

请注意,我将"a"和"b"字段声明为"val".如上面的a.a行所示,这使它们可访问.实际上,我建议将A设置为"case class",例如. case class(a: Int, b: Int)会自动将"val"添加到字段中,并且还会为您创建一个伴随类(另一个默认的"apply"方法使用两个Int).您还可以免费获得toStringequalshashcode的实现.

Note that I declared the 'a' and 'b' fields as 'val's. This made them accessible, as in the line a.a above. In fact, I would recommend making A a "case class", eg. case class(a: Int, b: Int) which automatically adds 'val' to the fields, and also creates a companion class for you (with another, default, "apply" method taking two Ints). You also get implementations of toString, equals, and hashcode for free.

这篇关于Scala元组的构造函数解包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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