MarcinAu
MarcinAu

Reputation: 612

Casting regex match to String

I created a simple code in Scala that checks whether an input is correctly formatted as HH:mm. I expect the code to result in an Array of valid strings. However, what I'm getting as a result is of type Any = Array(), which is problematic as when I try to print that result I get something like that: [Ljava.lang.Object;@32a59591.

I guess it's a simple problem but being a Scala newbie I didn't manage to solve it even after a good few hours of googling and trial & error.

val scheduleHours = if (inputScheduleHours == "") {
  dbutils.notebook.exit(s"ERROR: Missing param value for schedule hours.")
}
else {
  val timePattern = """^((?:[0-30]?[0-9]|2[0-3]):[0-5][0-9])$""".r
  val inputScheduleHoursParsed = inputScheduleHours.split(";").map(_.trim)
  
  for (e <- inputScheduleHoursParsed) yield e match {
    case timePattern(e) => e.toString
    case _ => dbutils.notebook.exit(s"ERROR: Wrong param value for schedule hours: '${inputScheduleHours}'")
  }
}

Upvotes: 0

Views: 66

Answers (1)

Tim
Tim

Reputation: 27356

The problem is that some branches return the result you want and others return dbutils.notebook.exit which (I think) returns Unit. Scala must pick a type for the result that is compatible with both Unit and Array[String], and Any is the only one that fits.

One solution is to add a compatible value after the calls to dbutils.notebook.exit, e.g.

val scheduleHours = if (inputScheduleHours == "") {
  dbutils.notebook.exit(s"ERROR: Missing param value for schedule hours.")
  Array.empty[String]
}

Then all the branches return Array[String] so that will be the type of the result.

Upvotes: 1

Related Questions