When should I use a Scala class and when to use Scala object in IDE? [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 4 years ago.
Improve this question
I have seen many cases where we can create a Scala project with only Scala object file and have our code inside it without the need of having a Scala class file.
I am currently working in a project where the Developer has written the code in the Scala object file (which acts as an object) instead of writing in a class file. To be more precise here is the screen shot of my IDE which shows that the code is written in an object file.
I want to know significance of writing a code in a Scala class and object file. What is the ideal scenario to use them?
There is a similar post available here which shows only the difference between a class and an object however I want to know when should I consider to use a Scala class and when to use a Scala object?

Use class when you want to create the same data structure multiple times with difference values. For example, a class could represent a row of data in a database application, or a client request in a web server.
Use object when you only need a single copy of the data structure in your program. For example, the command line for a program, or a data cache.
Classes can have short lifetimes, so use them for data that comes and goes. Objects always last until the program completes, so use them for data that needs to be available permanently.
It is reasonably straightforward to convert an object into a class, so start with an object unless you know that you are going to need multiple instances of the data.
If you just want to group similar functions or data (in a namespace), put it in an object.
If you want are writing code for a software library, use classes that can be created and deleted as required.
Note that this applies to top-level objects. An object can also be used as a class member or as a local value, but in this case it operates like a class in that it can have multiple instances and may have a limited lifetime.

An object is something that you can only have one in your program. It's most of the time used to contain functions or objects that don't change much. It's the equivalent of static in other languages
For instance:
object StringUtils {
val LF = "\n"
def toUpperCase(str: String) = str.toUpperCase()
}
// usage
StringUtils.toUpperCase("foo")
On the other hand, a class is something you can create with new. You can have several instances of a class in your program
class StringContainer(str: String) {
def toUpperCase() = new StringContainer(str.toUppercase())
}
// usage
val myString = new StringContainer("foo")
myString.toUpperCase()
For more detailed examples you can look at the scala documentation:
https://docs.scala-lang.org/tour/classes.html
https://docs.scala-lang.org/tour/singleton-objects.html
https://docs.scala-lang.org/tour/case-classes.html

Related

Catalyst FormFu DBIC error - using dot notation in a resultset [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 29 days ago.
Improve this question
I've inherited a Perl Catalyst application that I'm trying to port to a new server. The application uses FormFu with the HTML::FormFu::Model::DBIC module used to load data from a result set.
I have a DBIx table, say MyTable, with an auto-generated Result implementation and a custom ResultSet implementation. In the custom ResultSet implementation there are some subroutines, e.g. sub my_sub, that return filtered subsets of data.
In a FormFu YAML file, the following will fetch all the records from MyTable:
elements:
- type: Select
model_config:
resultset: MyTable
This is equivalent to fetching, in a Controller, $schema->resultset('MyTable'). This executes correctly on both the old server and the new server.
On the old server, I can use dot notation to call the subroutine to fetch the subset of records it returns like so:
elements:
- type: Select
model_config:
resultset: MyTable.my_sub
This is equivalent to fetching in a Controller, $schema->resultset('MyTable')->my_sub. This executes correctly on the old server. On the new server, in FormFu, this throws the error:
Can't find source for MyTable.my_sub at /[...]/HTML/FormFu/Model/DBIC.pm
I've added debugging to the FormFu DBIC.pm module to see if it's doing anything special. The code it calls is $schema->resultset($rs_name); where rs_name is the name given in the resultset parameter, "MyTable.my_sub", and $schema is of type Moose::Meta::Class::__ANON__::SERIAL, which I assume is some kind of wrapper. Within a Catalyst controller, a schema is of type myapp::Schema.
What am I missing? Is there some configuration option I need to set? Some module I need to install? I can't find any documentation or examples that show a FormFu resultset with dot notation, yet on the old server it works.
When I attempted to add logging to the working DBIC.pm file, I discovered that the developer from whom I inherited this application symlinked the module's DBIC.pm file to a custom DBIC.pm file in his own home folder with the extended functionality.

Dart - How to access global scope? [duplicate]

This question already has answers here:
How can I call a function from a method of the same name?
(3 answers)
Closed 12 months ago.
The simple actual question is
How to access GLOBAL scope in Dart?
Below is just the answer why I'm looking for it.
I have a problem which requires me to learn about Dart's scope resolution from here but unfortunately I can't find the solution for my problem, not even from Google or here, which was surprising me to have to open this question.
Dart allows user to exclude the this. on member variable access within class's scope so if two potentially conflicted variables need to share the same name, they need to be differentiated with scope operator and reference.
I need to define a class with member variable print where there is also global function print being called somewhere within the class. Of course print() => print(...) will returns error so I'm expecting something as simple as print() => global.print(..) but neither that is working.
I know there's workaround to solve it but please I need a straightforward one if any. Thank you.
you could add this line at the top of your file:
import 'dart:core' as core;
Then you would be able to refer to print as core.print(...);
The problem is that now you would have to use core. for every primitives like int, example:
core.int variable = 1;
I think this is not worth it and it's better to use another name for your print method.

Need an example for play2-elasticsearch module used with slick

I want to use https://github.com/cleverage/play2-elasticsearch in my play project where I am using slick2.0 for database interactions. But unfortunately I can't find any proper documentation or example which could help me get started.
I don't know well Slick, but I suppose that your data is represented as case class instances.
In this case, you can look at the Scala sample of the module, especially, the IndexTest class : https://github.com/cleverage/play2-elasticsearch/blob/master/samples/elasticsearch-scala/app/indexing/IndexTest.scala . First, you will see that your case class needs to extend the Indexable trait. Then that you have to define an IndexableManager for your class that is used to specify the ES type to use and the Json reads and writes for converting your data (you can just use the Json.reads / Json.writes macro for a basic usage).
Then you can look at the sample controller that show the usage of the IndexableManager to index, delete and search indexed data : https://github.com/cleverage/play2-elasticsearch/blob/master/samples/elasticsearch-scala/app/controllers/Application.scala

How to create a scala class based on user input?

I have a use case where I need to create a class based on user input.
For example, the user input could be : "(Int,fieldname1) : (String,fieldname2) : .. etc"
Then a class has to be created as follows at runtime
Class Some
{
Int fieldname1
String fieldname2
..so..on..
}
Is this something that Scala supports? Any help is really appreciated.
Your scenario doesn't seem to make sense. It's not so much an issue of runtime instantiation (the JVM can certainly do this with reflection). Really, what you're asking is to dynamically generate a class, which is only useful if your code makes use of it later on. But how can your code make use of it later on if you don't know what it looks like? For example, how would your later code know which fields it could reference?
No, not really.
The idea of a class is to define a type that can be checked at compile time. You see, creating it at runtime would somewhat contradict that.
You might want to store the user input in a different way, e.g. a map.
What are you trying to achieve by creating a class at runtime?
I think this makes sense, as long as you are using your "data model" in a generic manner.
Will this approach work here? Depends.
If your data coming from a file that is read at runtime but available at compile time, then you're in luck and type-safety will be maintained. In fact, you will have two options.
Split your project into two:
In the first run, read the file and write the new source
programmatically (as Strings, or better, with Treehugger).
In the second run, compile your generated class with the rest of your project and use it normally.
If #1 is too "manual", then use Macro Annotations. The idea here is that the main sub-project's compile time follows the macro sub-project's runtime. Therefore, if we provide the main sub-project with an "empty" class, members can be added to it dynamically at compile time using data that the macro sees at runtime. - To get started, Modify the macro to read from a file in this example
Else, if you're data are truly only knowable at runtime, then #Rob Starling's suggestion may work for you as it did me. I'll share my attempt if you want to be a guinea pig. For debugging, I've got an App.scala in there that shows how to pass strings to a runtime class generator and access it at runtime with Java reflection, even define a Scala type alias with it. So the question is, will your new dynamic class serve as a type-parameter in Slick, or fail to, as it sometimes does with other libraries?

Compile error when setting class in VBA [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I copied code from here but I'm getting an error when trying to run the code.
The problem would be in:
Public NextItem As New queueItem
and the error message is:
user-defined type not defined
Is my VBA version not right to do this or am I doing something wrong?
You probably mean this link? The one you provided has the alternative implementation (with arrays, not with references).
I got it to work for me. Steps:
Right click on the VBA project file name, and go to Insert-> Class Module:
Click F4. The Properties window appears. Then go to the class Name and change it to Queue:
Copy and Paste the Queue Class code you found at the web site. Repeat the previous and this step for the QueueItem class (i.e., insert a Class Module, name it QueueItem and copy the code inside that class module).
This time, insert a Module using the same process (not a Class Module, but rather a simple Module). You do not need to give your module a name, Module1 will be OK.
Copy the Sub TestQueue() inside the module and run it. It should work. If you use Option Explicit on your module, you will get an error that element is undefined. So we need to define it: Dim element as Variant, under the first few Dim statements of the subroutine. Then it should run.
The above worked for me, let me know if I can be more precise, or send the file to you.