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 last year.
Improve this question
Is a trait a good way to put together all the constants that will be used by certain classes?
Or is there maybe a better way to handle constants, like a package object?
Singleton objects can contain fields, like any other object. If a constant exists on its own, it makes sense to put it in a singleton. Don't make a singleton just for all constants, but if they're logically grouped together, then you could pretty easily make an object with a good name.
object Calendar {
val DaysInYear = 365
val DaysInWeek = 7
val EpochYear = 1970
// ... etc ...
}
Package objects are deprecated in Scala 3 and set to be removed in the future. If you're already using Scala 3, then you can just put individual constants at the top-level of a file. Otherwise, throwing them in a singleton is the most future-proof way to code right now.
Related
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.
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.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Both tuples and list are accepting the different type values as attached in snippet, then what is the main difference?
Scala is a typed language. You want your program to know as much as possible about the shape of the data it is working with.
List[Any] is not a very useful type. It does not tell you that there are three elements in there, and what their respective types are.
(Int, Double, String) tells you much more.
Lists are for collections of elements of all the same type (but unknown number).
Tuples are for the combination of a fixed number of elements (that can each have their own type).
Tuples can also be seen as ad-hoc versions of case classes (which you have to define first, but then give you named fields, and methods and all that):
val myData = FooDataRecord(id = 1, amount = 1.1, name = "a")
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 5 years ago.
Improve this question
There is a web app that uses the following stack on the server:
akka-persistence/service-layer/akka-http (for REST)
The question is :
how can I - in the most elegant, most dry way - make sure that only those users can execute a function in the service layer who are authorized to do so (under the given input parameters).
So for example let's take the simple example:
getEntity(userID:UserID, ref:EntityID):Entity = ???
how should I modifiy getEntity such that only those users are allowed to execute it where the userID of the caller is the same as the userID in the parameters?
What is the most elegant, composable, dry way to do this in general ?
Using custom monads?
Using continuation monads?
Using akka-http style directives?
Using implicits?
Using Free-Monads?
Using Arrows?
Using Kleiesly ?
I cannot really imagine.
How I would do it would be to use an implicit context:
getEntity(userID:UserID, ref:EntityID)(implicit c: Context): Entity = ???
and then whatever is in the context is up to you, i.e.
trait Context {
def canExecute(userId: UserID): Boolean
}
You may want to break this out so you have roles, permissions, etc. Also, if you are using a type parameter then you can use a context bound and make it a bit cleaner:
trait Context[A] { ... }
def getEntity[A: Context](userID:UserID, ref:EntityID): Entity = ???
Implicit parameters are great for being able to pass through contextual information like "current security context" or "correlation id" that is not core to the domain logic but has to be involved all the way down the stack.
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)