Scala 中的构造器局部变量 [英] Constructor-local variables in Scala

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

问题描述

我正在练习不耐烦的 Scala"的练习 5.7,我需要创建一个类 Person,它在构造函数上采用 name:String 并具有 2 个属性 firstNamelastName 由空格分隔的名称填充.我的第一次尝试是:

I'm on exercise 5.7 of "Scala for the Impatient", where i need to create a class Person that takes a name:String on constructor and has 2 properties firstName and lastName filled from name split by whitespace. My first trial was :

class Person(name:String) {
  private val nameParts = name.split(" ")

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

问题是,现在 nameParts 仍然是一个在类中始终可见的私有字段,而实际上应该只存在于构造函数的本地环境中.我想要的 Java 等价物是:

The problem is, that now nameParts remains as a private field always visible within the class, when in fact should only exist within the constructor's local environment. The Java equivalent of what I want would be:

 class Person{
    private final String firstName;
    private final String lastName;

    Person(String name){
        final String[] nameParts = name.split(" ");
        firstName = nameParts[0];
        lastName = nameParts[1];
    }
 }

在这里,nameParts 只存在于构造函数中,这就是我的目标.关于如何在 Scala 中完成此操作的任何提示?

Here, nameParts exists only withing the constructor, which is what i'm aiming for. Any hints on how this can be done in Scala?

注意:我最终找到了一种更Scalesque"的方式:

NOTE: I ended up finding a more "Scalesque" way:

class Person(name:String) {
    val firstName::lastName::_ = name.split(" ").toList 
}

但我仍然想得到我的问题的答案.

but I still would like to get an answer to my question.

推荐答案

有一种方法可以避免 private val.只需使用 Array 的提取器:

There is a way to avoid the private val. Just use the extractor of Array:

class Person(name: String) {
  val Array(first, last) = name.split(" ")
}

你想要做的事情可以通过同伴上的工厂方法和一个以 first 和 last 作为参数的默认构造函数来实现:

What you want to do can be achieved through a factory method on the companion and a default constructor that takes first and last as param:

class Person(val first: String, val last: String)

object Person {
  def apply(name: String) = {
    val splitted = name.split(" ")
    new Person(splitted(0), splitted(1))
  }
}

scala> Person("Foo Bar")
res6: Person = Person@37e79b10

scala> res6.first 
res7: String = Foo

scala> res6.last
res8: String = Bar

但对于这个简单的案例,我更喜欢我的第一个建议.

But for this simple case I would prefer my first suggestion.

您链接中的示例也可以使用,但它与我的第一个示例大致相同.Afaik 无法在构造函数中创建临时变量.

The example in your link would also work, but it's kind of the same as my first example. Afaik there is no way to create a temporary variable in the constructor.

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

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