Scala local variable inside primary constructor

本小妞迷上赌 提交于 2019-12-06 02:16:39

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))
  }
}

It is not a general answer, but in this particular way you may write:

  val Array(firstName, lastName) = firstLast.trim.split(" ")

You don't strictly need the intermediate variable:

class Person(firstLast: String) {
  val (firstName, lastName) =
    firstLast.trim.split(" ") match {case Array(first, last) => (first, last)}
}

However, if your transformation from firstLast to firstName and lastName grows a big longer, for example, because you check that there is exactly one first and one last name, then I would encapsulate the whole splitting-business in a dedicated method:

class Person(firstLast: String) {
  val (firstName, lastName) = split(firstLast)

  private def split(firstLast: String): (String, String) = {
    val firstLastAsArr = firstLast.trim.split(" ")
    ...
    (first, last)
  }
}

Pattern matching in constructor works just fine, but you should consider moving such logic from constructor to factory method:

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

val p = Person("My Title")

Pattern maching in primary constructor works well

  class Person(_fullName:String) {
    val (firstName, lastName) =  _fullName.split(" ") match {
      case Array(x:String, y:String, _*) => (x,y)
      case _ => (null,null)
    }
  }

See my github for full answer https://github.com/BasileDuPlessis/scala-for-the-impatient/blob/master/src/main/scala/com/basile/scala/ch05/Ex07.scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!