[Solved] Why does the absence of an else block translate to Unit type return for a function?

I can correct this by adding the else clause, but how come if there is no outcome handled by default, the function tries to return a Unit? In Scala, unlike more “imperative” languages, (almost) everything is an expression (there are very few statements), and every expression evaluates to a value (which also means that every … Read more

[Solved] Understanding map in Scala [closed]

1. .map in functional programming applies the function you want to each element of your collection. Say, you want to add some data to each element in an array you have, which can be done as below, scala> val data = Array(“a”, “b”, “c”) data: Array[String] = Array(a, b, c) scala> data.map(element => element+”-add something”) … Read more

[Solved] Extract text using regular expression between keywords

You haven’t described your requirements very well. It looks like a simple substring formula is all you need. val str = “[CS]v1|<bunch of alpha numberic text>[CE]” val extract = str.substring(7, str.length-4) But if you really want to use regex this might do. val str = “[CS]v1|<bunch of alpha numberic text>[CE]” val extractor = “[^|]+\\|(.*)\\[..]”.r val … Read more

[Solved] When to use return statements in Scala?

The key is to understand in Scala if-else expressions are just that – expressions, not control structures. Hence if (x == 5) “equal to 5″ does not mean “if x equals five, then return five”, instead it means something like “if x equals five, then evaluate this expression to five, otherwise evaluate to uknown value.” … Read more

[Solved] toDF is not working in spark scala ide , but works perfectly in spark-shell [duplicate]

To toDF(), you must enable implicit conversions: import spark.implicits._ In spark-shell, it is enabled by default and that’s why the code works there. :imports command can be used to see what imports are already present in your shell: scala> :imports 1) import org.apache.spark.SparkContext._ (70 terms, 1 are implicit) 2) import spark.implicits._ (1 types, 67 terms, … Read more

[Solved] Einstein’s puzzle in Scala [duplicate]

val houses = List(1, 2, 3, 4, 5) val orderings = houses.permutations.toList val List(first, _, middle, _, _) = houses def imright(h1: Int, h2: Int) = h1 – h2 == 1 def nextto(h1: Int, h2: Int) = math.abs(h1 – h2) == 1 for (List(red, green, ivory, yellow, blue) <- orderings if imright(green, ivory)) for(List(englishman, spaniard, … Read more

[Solved] Java / Scala – how to convert string to long?

java.sql.Timestamp (a subclass of java.util.Date) uses milliseconds for time while the Unix timestamp counts seconds. If you have a Unix timestamp you need to multiply it by 1000 (and divide by 1000 to get a Unix timestamp from a Java Date). solved Java / Scala – how to convert string to long?