如何在Scala的主要构造函数中定义局部var/val? [英] How do you define a local var/val in the primary constructor in Scala?

查看:195
本文介绍了如何在Scala的主要构造函数中定义局部var/val?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中,类的主构造函数没有显式主体,但从类主体隐式定义.那么,如何区分字段和局部值(即,构造函数方法局部的值)?

In Scala, a class's primary constructor has no explicit body, but is defined implicitly from the class body. How, then, does one distinguish between fields and local values (i.e. values local to the constructor method)?

例如,采用以下代码段,这是"Scala编程"中一些示例代码的修改形式:

For example, take the following code snippet, a modified form of some sample code from "Programming in Scala":

class R(n: Int, d: Int) {
   private val g = myfunc
   val x = n / g
   val y = d / g
}

我的理解是,这将生成一个包含三个字段的类:私有"g"和公共"x"和"y".但是,g值仅用于x和y字段的计算,没有超出构造函数范围的含义.

My understanding is that this will generate a class with three fields: a private "g", and public "x" and "y". However, the g value is used only for calculation of the x and y fields, and has no meaning beyond the constructor scope.

那么在这个(当然是人为的)示例中,如何为该构造函数定义局部值?

So in this (admittedly artificial) example, how do you go about defining local values for this constructor?

推荐答案

例如

class R(n: Int, d: Int) {
  val (x, y) = {
    val g = myfunc
    (n/g, d/g)
  }
}

这篇关于如何在Scala的主要构造函数中定义局部var/val?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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