How to run a scala program in terminal on mac? [closed] - scala

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 2 years ago.
Improve this question
I built an object which is supposed to serialize and deserialize a file. I built it in scala in terminal on mac. I'm new to scala and don't have that much programming experience in general. I was wondering how I could run the object so that it performs the task I assigned it to do. Might be a dumb question but I don't know what to do. Here's an image of what my object is

Enter in terminal (repl)
serializationTest3.main(Array())
"Running" an object is actually executing the method main(Array[String]): Unit of the object.
Extending trait App
object X extends App {
foo()
}
is like wrapping the object body with method main
object X {
def main(args: Array[String]): Unit = {
foo()
}
}
https://www.scala-lang.org/api/2.13.3/scala/App.html
How Scala App trait and main works internally?
Difference between object with main() and extends App in scala
Difference between using App trait and main method in scala

Related

Simple Scala program not executing on command prompt [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 9 months ago.
Improve this question
This is some of the strange issue, the program is only printing hello scala, but it seems that I am getting syntax weird error. Please correct me if I miss anything
Program
object hello{
def main(args:Array[String]){
println("Hello Scala")
}
}
Error:- '=' expected, but '{' found
As the error message suggests, you need a = before the {:
def main(args: Array[String]) = {
println("Hello Scala")
}
The syntax you used was originally supported so you might see it in some example code. But it was deprecated in later versions and is now no longer allowed.

What is DSL in Scala? [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 4 years ago.
Improve this question
Going through various Scala related material, term DSL is used at many places.
Google search tells it is Domain specific language.
What exactly it means, and why is it that this term doesn't comes across while learning other languages like Java?
As others have pointed out, the first part of the question ("what is a DSL?") is essentially answered by What is a DSL and where should I use it?
I'll try to answer instead to the second part: why are DSLs so popular in Scala?
The reason is that Scala (as opposed to other languages like Java) offers many syntactic facilities to provide DSLs.
For example, Scala has infix method applications:
someObject.someMethod(someArgument)
// can be written as
someObject someMethod someArgument
This makes introducing custom "operators" very easy in the language. A notable example is the akka DSL for sending messages to an actor:
actor ! message
which is a DSL mimicking the syntax of Erlang.
Another example of a syntactic facility in Scala is the "trailing block argument" (not sure it has a precise name):
def someMethod(x: Int)(y: String) = ???
// can be invoked as
someMethod(42)("foo")
// but also as
someMethod(42) { "foo" }
which is very interesting when the last parameter is a function:
def someOtherMethod[A, B](x: A)(f: A => B): B = ???
someOtherMethod(42) { a =>
// ...a very long body
}
In other languages, blocks ({ ... }) are usually reserved to built-in control-flow structures (such as if, while, for, etc), but in Scala you can use this syntactic facility to build custom methods that resemble built-in control structures.
Those two features alone are distinctive enough for explaining why DSL are so pervasive in the Scala community.
Digging a bit deeper, we can also mention implicit conversions, which allow to add custom methods to any existing type. For example
implicit class TimesOps(x: Int) {
def times(y: Int): Int = x * y
}
// then use as
2 times 4 // 8
This example combines the use of infix method application and implicit conversions.

access/authorization control : akka-persistence/service layer/akka-http stack [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 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.

What's the advantage of using Macros (instead of functions) is 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 7 years ago.
Improve this question
What are macros used for in Scala? What can be done with a Macro that cannot be done with a function?
I suppose one advantage are:
The ability to parse the AST at the call point, but that's a fairly rare use case.
The code doesn't result in an extra function call (modifying the AST directly instead), but modern compilers are pretty good at inlining functions.
Are there any other advantages I'm missing?
I agree with Daenyth, macros have some modest but useful benefits for code-gen.
For arguments sake, consider a spectrum of what play-json could have done to generate code:
A) Two Dumb Runs:
read-in a case class definition as a string, and write back out
updated strings
use the updated definition in the "real" run.
This is wonderfully simple at first, but clunky and not type-safe
B) Trees and Tasks: read the def in as a string, but use a runtime code-gen library like Treehugger to write code as trees, and an build-tool plugin to add the code-gen task to 'compile'
This gets us halfway type-safety, and sequential compilation by using a plugin offers at least an illusion of a single run.
C) Macros: use an experimental feature to read and write trees at compile time
Macros are fully type-safe, single run, and having everything happen in a single compilation means easily modifying generated code.
For Example
Say I use a code-gen library that adds def printType to case class Record(x: Int), giving
case class Record(x: Int) {
def printType = println("Int")
}
Now say I want to add my own def goodbye to the class as well:
Without macros: I could either
1) attempt to modify the output to
case class Record(x: Int) {
def printType = println("Int")
def goodbye = println("bye")
}
but then I encounter this is a generated file, DO NOT EDIT printed at the top of the output file, reminding me that the file will be overwritten, so I'll either have to go to the hassle of toggling off code-gen somehow, or
2) attempt to modify the input to
case class Record(x: Int) {
def goodbye = println("bye")
}
but then the code-gen library probably won't see arbitrary code, so I would have to modify the code-gen library itself.
With macros: if the code-gen library relies on macros (and the library doesn't explicitly dispose of the class body), I can add my new def to the input
case class Record(x: Int) {
def goodbye = println("bye")
}
and it just works; my def is there, the generated def is there too.
case class Record(x: Int) {
def printType = println("Int")
def goodbye = println("bye")
}
The advantage of macros is seen most when it prevents you from writing code in the first place.
Consider the case of play-json. I can define a case class, and the play-json formatter macros can create methods which convert my CC to and from json using the fields I've defined on the class.
The key thing here is that it's taking part of the source code which is not usually represented at runtime (the names of the variables) and it does compile-time (type-safe!) reflection on them to create specific functions instead of using runtime (unsafe) reflection.

Why use Specs2 over JUnit? [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 7 years ago.
Improve this question
We went through online material such as scalatest site. What are advantages of using scala testing framework Specs2? How does it add to the project over JUnit?
I'm a little reluctant to answer this because it's a quite subjective thing.
But I could summarise it as "In the same way Scala gives you new and cleaner ways to solve problems over Java, Specs2 gives you new and cleaner ways to test over JUnit".
Some quick examples:
Mockito is a first-class citizen
Mockito is my favourite JVM mocking library; using it with Specs2 is as simple as mixing in a trait and you get a nice DSL for verification:
class MySpec extends Specification with Mockito {
// Setup:
val mockConnection = mock[Connection]
...
// Verification: (in a test)
there was one(mockConnection).get("www.google.com")
}
ScalaCheck is a first-class citizen
ScalaCheck can save a heap of time "fuzzing" inputs to your functions, and again, a simple trait mixin gets you all of its power within your Specs2 tests.
Run a test in a Scope
Ever had a problem where tests would work on your machine but break elsewhere, because your machine ran them in a certain order? Or got into "mocking hell" due to interactions between stubbed collaborator behaviour? Specs2 lets you put the entire test into a Scope to contain all of that state and stop it from leaking into other tests:
class AnotherSpec extends Specification with Mockito {
class FooScope extends Scope {
val mockResponse = mock[Response]
val mockConnection = mock[Connection]
...
mockConnection.execute returns mockResponse
def frobulate(s:String) = {
// Use mockResponse, mockConnection, etc ...
}
}
"My thing" should {
"Do stuff" in new FooScope {
frobulate("hello")
there was one(mockConnection).post(...)
}
}
Scopes help you DRY up your tests as well as stop state leaks between them.
Plus
"Blocks" to group related tests ("My thing" should)
Readable, space-separated test names ("throw an exception if argument < 0" in)
Readable DSL for matching (result must have length(7))
Matchers for Scala-idiomatic types (result must beNone)
Easily temporarily disable a test with pending
Generate HTML reports/output with a DSL
Downsides
In an attempt to make this answer slightly more objective, I should also point out this article by the esteemed Bill Venners about compile time which points out that a Specs2 mutable.Specification, due to large numbers of implicits and function declarations, is almost an order-of-magnitude slower to compile than a roughly-equivalent JUnit test. It also does not scale well over large numbers of tests. Or at least it didn't when the article was written in early 2013. There are now approaches you can use to address this.