Scala Option: isDefined vs map based approach [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 11 months ago.
Improve this question
I have a piece of code implemented in 2 ways:
val c = if(x.y.isDefined){
methodA(....)
} else {
method(....)
}
c
And this:
val c = x.y.
map(methodA(....))
.orElse(Some(mehodB(....))
.getOrElse("")
c
x.y is an Option and methodA, methodB return String values.
Which of these approaches is more preferred in Scala? Personally I find first one to be more easy to understand, but my more scala proficient colleague prefers second one.

use the if or something based on pattern match (by the way, no need for assigning to c if you return the expression)
x.y match {
case Some(_) => methodA()
case None => methodB()
}

x.fold(methodB) { _ => methodA }

Related

How can I write a function which gets a Map[Char, Int] as an input and makes a Set[Case Class]? [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 1 year ago.
Improve this question
Found this stepik task and have no idea what to do:
Write a function which gets a Map[Char, Int] as an input and makes a Set[LetterTree] (LetterTree is the case class below), in which from each (c,w) map entry, we make a LetterLevel(c,w), then we then put it in the said Set[LetterTree].
trait LetterTree {
def weight: Int
}
case class LetterLevel(ch: Char, weight: Int) extends LetterTree
object TreeBuild extends App {
def TreeSetBuild(freqs: Map[Char,Int]): Set[LetterTree] = ???```
}
You could use tupled to construct LetterLevel instances from the tuple elements of the Map:
object TreeBuild extends App {
def treeSetBuild(freqs: Map[Char,Int]): Set[LetterTree] =
freqs.map(LetterLevel.tupled).toSet
}
TreeBuild.treeSetBuild(Map('a'->1, 'b'->2, 'c'->3))
// res1: Set[LetterTree] = Set(LetterLevel(a,1), LetterLevel(b,2), LetterLevel(c,3))

Purpose of "this" in Kotlin classes [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
I'm trying to work out the purpose of this in classes. Consider the following example:
class TestMe {
var a: Int = 1
var b: Int = 2
fun setValA(value: Int) {
this.a = value
}
fun setValB(value: Int) {
b = value
}
}
val testInstance1 = TestMe()
val testInstance2 = TestMe()
testInstance1.setValA(3)
testInstance1.setValB(4)
println("instance 2A: ${testInstance2.a}, instance 2B: ${testInstance2.b}") // 1 2
println("instance 1A: ${testInstance1.a}, instance 1B: ${testInstance1.b}") // 3 4
It seems that I can simply omit this value and the results will be the same. Is there anything that I'm missing here?
Many thanks!
Yes, same as Java, but you will have a problem if a is the parameter name also:
fun setValA(a: Int) {
a = a
}
Compilation error:
Val cannot be reassigned
Then you will have to use this:
fun setValA(a: Int) {
this.a = a
}
In addition to user7294900's answer, this can only be omitted in this.<property or method name>, and there are plenty of other uses: e.g. this::class, or
fun doSomething(other: OtherClass) {
other.doSomethingWith(this)
}

what is this scala grammar [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 3 years ago.
Improve this question
what is this grammar? What function was called?
Does this grammar have a name?
val indataRDD = sc.makeRDD(Array("1,jack,15","2,Lily,16","3,mike,16"))
val rdd = indataRDD.map( _.split(',') ).map{
arr => {
val put = new Put(Bytes.toBytes(arr(0)))
put.addColumn(Bytes.toBytes("cf"),Bytes.toBytes("name"),Bytes.toBytes(arr(1)))
put.addColumn(Bytes.toBytes("cf"),Bytes.toBytes("age"),Bytes.toBytes(arr(2).toInt))
***(new ImmutableBytesWritable, put)***
}
}
This is syntax sugar to create a tuple of two elements.
The line (new ImmutableBytesWritable, put) is therefore equivalent to new Tuple2(new ImmutableBytesWritable, put)

List("foo") foreach print other synonyms? [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 4 years ago.
Improve this question
I want to put the print behind
like
"foo" match {
case str => println(str)
}
or
List("foo") foreach print
Are there other best one?
like in Haskell
return "foo" >>= print
so if you just want to have somewhat haskell like semantics you can try the cats or the scalaz libraries. both have IO monads (cats in cats-effects) that would allow you to use the print in a principled manner as in your last example. If you don't care about the purity aspect you could also achieve this with the Id Monad which also both libraries offer.
You can do this:
case class Print(v: String) {
def print = Predef.print(v)
}
object Print {
implicit def stringToString(s: String) = new Print(s)
}
import Print._
object App extends App {
"foo".print
"bar" print
}

What does the scala case class equality function do? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
According to this, Scala case classes automatically generates an equality method. However:
class SomeCaseClass(val string:String) {}
val a = "123"
assertTrue( a.equals( a ) ) // Passes
assertTrue( new SomeCaseClass(a).equals( new SomeCaseClass(a) ) ) // Fails, Scala 2.10
So, what does this automatically generated equals method do?
It's not a case class. That's the case class:
scala> case class SomeCaseClass(string: String)
defined class SomeCaseClass
scala> val a = "123"
a: String = 123
scala> SomeCaseClass(a) == SomeCaseClass(a)
res1: Boolean = true
== is just a syntax sugar for equals
In your example, you've just called equals (you'll get same result with ===) on regular object (this equals is not automatically generated), so it checked just referential equality.
P.S. You may notice that case class doesn't require new as it has automatically generated companion object. It doesn't require val in constructor as it assumes it by default. {} isn't mandatory for both regular and case classess.