fuzzylogical
fuzzylogical

Reputation: 892

What is a more Scala way of writing this code?

I want to strip off the word "America/" from the start of each item in the list, and the code below does just that, but I feel like it can be done in a significantly better way.

var tz = java.util.TimeZone.getAvailableIDs
for(i <- 0 until tz.length) {
    if(tz(i).startsWith("America/")) {
        tz(i) = tz(i).replaceFirst("America/", "")
    }
}

Upvotes: 1

Views: 297

Answers (8)

Alvaro Carrasco
Alvaro Carrasco

Reputation: 6172

No regex:

val tz = java.util.TimeZone.getAvailableIDs.map(_ stripPrefix "America/")

Upvotes: 0

RidingRails
RidingRails

Reputation: 792

Added an 'if' to the for/yield

val zones = java.util.TimeZone.getAvailableIDs
val formatted_zones = for(i <- 0 until zones.length if zones(i).startsWith("America/")) yield {
  zones(i).replaceFirst("America/", "")
}

Upvotes: 0

Noah
Noah

Reputation: 13959

Simple and straight forward:

val tz = java.util.TimeZone.getAvailableIDs.map(_.replaceFirst("^America/", ""))

Upvotes: 3

Mika&#235;l Mayer
Mika&#235;l Mayer

Reputation: 10701

very similar to @Noah's answer, but using a for-yield iteration (so that you can add other filters with no more usage of parentheses).

import java.util.TimeZone
val tz = for(t <- TimeZone.getAvailableIDs) yield t.replaceFirst("^America/", "")

Upvotes: 2

Chris Martin
Chris Martin

Reputation: 30736

If you only want the American time zones, you could do this:

val americanZones = {
  val pattern = "^America/(.*)".r
  ( java.util.TimeZone.getAvailableIDs
    flatMap pattern.findFirstMatchIn
    map (_ group 1) )
}

Upvotes: 0

Windor C
Windor C

Reputation: 1120

this can work:

val tzs = java.util.TimeZone.getAvailableIDs map { tz =>
  if(tz.startsWith("America/")) tz.replaceFirst("America/","")
  else tz
}

Upvotes: 0

iMom0
iMom0

Reputation: 12921

I will use regex for it:

val pattern = "^America/".r
tz = tz.map(pattern.replaceFirstIn(_, ""))

wonder if it is an effcient way.

Upvotes: 1

Tritlo
Tritlo

Reputation: 549

Map is preferred to for loops in functional programming, so instead of changing the list in place with a for loop, passing the data around by mapping is more pure and (IMO) prettier.

Upvotes: 0

Related Questions