主要构造函数中的Scala局部变量 [英] Scala local variable inside primary constructor

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

问题描述

如何在Scala中如何在主构造函数中定义局部变量?

How in Scala I can define local variable in primary constructor?

我需要从Scala for the impatient书中解决此练习:

I need to solve this exercise from Scala for the impatient book:

用一个接受字符串的主要构造函数编写一个Person类 包含名字,空格和姓氏,例如new 人(弗雷德·史密斯").提供只读属性firstName和 姓.主构造函数参数应为var,val还是 一个普通的参数?为什么?

Write a class Person with a primary constructor that accepts a string containing a first name, a space, and a last name, such as new Person("Fred Smith"). Supply read-only properties firstName and lastName. Should the primary constructor parameter be a var, a val, or a plain parameter? Why?

现在,我的解决方案如下:

And for now my solution looks like this:

class Person(firstLast: String) {
  private[this] val firstLastAsArr = firstLast.trim.split(" ")

  val firstName = firstLastAsArr (0)
  val lastName = firstLastAsArr (1)
}

如何将firstLastAsArr变量的可见性限制在主要构造函数范围内(现在它具有类范围)?

How I can restrict firstLastAsArr variable visibility to primary constructor scope (now it have class scope)?

推荐答案

一种解决方案是立即初始化firstNamelastName,从而允许将firstLastAsArr转换为初始化块内的本地临时值:

One solution is to initialize firstName and lastName at once, thereby allowing to turn firstLastAsArr into a local temporary value inside your initialization block:

class Person(firstLast: String) {
  val (firstName, lastName) = {
    val firstLastAsArr = firstLast.trim.split(" ")
    (firstLastAsArr(0), firstLastAsArr(1))
  }
}

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

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