scala get vs match which one to use, given that restult will always be same type? [closed] - scala

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Given that match will never be None,
Which style is better or can I improve the first?
val tmp = (cols.find(_(0) == id).get)
SomeClass(tmp(0), tmp(1))
cols.find(_(0) == id) match {
case Some(value)=> SomeClass(value(0), value(1))
case None=> NotFound("Given id not found")
}

Since this a question about style, my answer is that neither of these is the best style. Instead, just keep the value in the Option
val opt: Option[SomeClass] = cols.find(_(0) == id).map(v => SomeClass(v(0), v(1)))
Keep processing/testing inside the Option using foreach/exists etc. until you really need the bare value. There is a very rich set of methods on Option that covers most of the things that are needed.
If the rest of the code is structured well, you will likely find that the value never needs to be extracted in a separate operation.

Related

Print only unique element from a list in scala [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Consider the following list(1,1,2,2,3,4,4,5,5) I want to print only 3. Since it is the unique one. Can someone help me with the Scala code.
It's not a Spark question, but this function would do it for Scala
def uniqueElems[T](lst: Seq[T]) = {
lst.groupBy(identity).collect { case v if v._2.length == 1 => v._2.head }
}

How can i derive values list of values from list of either using flatmap for fold? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
im trying to convert a scala list of eithers, as such:
List(Left(3),Left(4),Left(1),Left(5))
Into a either of a list Either[List[Int],Int] like this?
Left(3,4,1,5)
Only using flatmap, map or fold?
ive been hammering at it for a while now and can simply not make it work
Assumed:
val a = List(Left(1), Left(2), Left(3)) // for example
Then following will return a Left[List[Int]]:
Left(a.map(_.value))
// Left(List(1, 2, 3))
Then you can extract the values out of the list, which I don't thin is generally a good idea.

Scala equivalent for Java stream findFirst, filter, map [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have java code shown below, how to convert it to scala?
feature.getFeatures()
.stream()
.filter(a -> a.getFeatureName().equals(feature))
.findFirst()
.map(f -> f.Accounts().contains(accountId))
.orElse(true);
Whenever you see filter or find chained with map, think collect or collectFirst
So something like this should work:
feature.getFeatures()
.collectFirst {
case f if f.getFeatureName().equals(feature) =>
f.Accounts().contains(accountId)
}.getOrElse(true)

How to best way to parse args yet make it clear and easy to understand [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm putting some test cases and having lots of parameters yet it is cumbersome and not so easy to understand putting them into a liner in scala. I rather specify in a visually acceptable manner but correctly parse them in scala...
I would use String Interpolation to define the arguments such as below
val kafkaServers = "server1:9092,server2:9092"
val pleasentArgs = s"""
--master='spark://someserver'
--metricWindowSize=50
--outputDirectory='/tmp/someGoodDirectory'
--zkQuorum=$zkQuorum
--saveToHDF=false
--userName='jack#somewhereElse.com'
--kafkaServers=$kafkaServers
"""
And have a method to clean up all the newline, tab etc characters and then generate the args as shown below:
def cleanUp(str:String) = str.split('\n').map(_.trim.filter(_ >= ' ')).mkString(" ")
def genArgs(args:String): Array[String] =cleanUp(args).split(" ").filter(!_.trim.isEmpty)
So eventually we can just call genArgs method
val args = genArgs(pleasentArgs)

use None or EmptyMyObj in scala? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I understand the concept of None
I also understand how nice it is to have MyObj and also MyEmptyObj but i cant figure out when its better to use None instead of MyEmptyObj and when I should be using MyEmptyObj instead of None. Also I tend not to like to see methods that return Option[MyObj] it clutters my code I prefer to return MyObj and then seamlessly call its methods such as MyObj.toJson and thus MyEmptyObj.toJson will know to represent itself rather than having case None: return some empty json what do you think about this whole subject?
To the other side I can say that None goes very well with flatMap etc, so which to choose?
when to None
and when to Empty?
None is great when you have no default value, but if you have a default, by all means use it.
As a very simple example, if you wanted to define a function called amountOwed, you could do this:
def amountOwed(bill: Int, alreadyPaid: Option[Int]): Option[Int] = {
val owed = bill - alreadyPaid.getOrElse(0)
if(owed == 0) None // nothing to pay!
else Some(owed)
}
But that's much more complex (and annoying) than it needs to be, since 0 makes perfect sense as both a "haven't paid anything" and "don't owe anything":
def amountOwed(bill: Int, alreadyPaid: Int): Int = {
bill - alreadyPaid
}