How do I use POJO equivalents in Scala? - scala

Suppose I have the following
class SimpleClass (myInt: Int, myString: String) {
}
What is wrong with the following?
val mySimple = new SimpleClass(1, "hi")
println(mySimple.myInt)

If you want the contructor parameters to be available as fields of the class, you have to declare them as vals or vars:
class SimpleClass (val myInt: Int, val myString: String) {
}

The java equivalent of your Scala definition is:
public class SimpleClass {
public SimpleClass( int myInt, String myString ) {
}
}
No wonders it doesn't work...
Hey dude, that's your 17th scala question and you are still troubled by the very basics of the language. Perhaps you should take an afternoon and read some of tutorial on-line (or some book) to consolidate your knowledge. I can suggest:
http://www.codecommit.com/blog/scala/roundup-scala-for-java-refugees
http://www.ibm.com/developerworks/java/library/j-scala02198/index.html (see listings 11-13)

For the full POJO experience™, including equality, hashCodes and sane implementation of toString... You'll want case classes:
case class SimpleClass(myInt: Int, myString: String)
val mySimple = SimpleClass(1, "hi")
println(mySimple.myInt)
Parameters to a case class are automatically made into vals. You can explicitly make them vars if you wish, but this this sort of thing is typically frowned upon in Scala - where immutable objects are favoured.

The problem is that you are calling the SimpleClass.myInt getter method but you didn't define a getter method anywhere. You need to define the SimpleClass.myInt getter method or even better yet, get Scala to automatically define it for you:
class SimpleClass(val myInt: Int, myString: String) {}

Related

Why this class need to be abstract in scala?

In java and c#,I can write this:
class Tree {
Tree left;
Tree right;
}
but in scala:
class Tree{
val left:Tree
val right:Tree
}
I need to add abstract for class,or write:
val left:Tree=new Tree()
I can write this:
trait Tree{
val left:Tree
val right:Tree
}
but why if I use class,I "have to"and abstract?I don't think it's a good design
Thanks!
The reason you can write
class Tree {
Tree left;
Tree right;
}
in Java and C# is because the fields are initialized to null by default (or to 0, etc. depending on the type). Scala's designers decided this is a bad idea and you need to initialize them. So the approximate Scala equivalent is
class Tree {
// note, not val
var left: Tree = null
var right: Tree = null
}
which is legal (but probably not something you actually want to use).
but why if I use class,I "have to"and abstract?
You have to mark your class with the abstract keyword because your class is abstract. It cannot possibly be instantiated.
I don't think it's a good design
Good design is subjective. The designers of Scala thought that being explicit in this case, rather than making the class automatically abstract was good design. I would guess that the majority of the Scala community agrees with them.
You disagree, and that is perfectly okay.
It happened because scala sometimes considers val and def as method like declarations. Let me elaborate, please, for instance, we have the next Scala example:
class Example {
val a: String = "example"
}
val example = new Example()
println(example.a)
You may see that a declared as a field. Unlike Java, we can change this declaration easily to def and everything remains compiling:
class Example {
def a: String = "example"
}
val example = new Example()
println(example.a)
In the case of Java (not sure about C# I've never worked with it), if you would like to access the field over getter method, you will need to change all invocation places from field to method access.
Now, you can consider val as let's say sort of eager cached def version - if so then declaring val without actually value assignment implicitly considered by compiler as declaring method without implementation and that's why compiler says Tree is an abstract class - because left and right has no values, hence they are abstract. In order to make it non-abstract, you need to assign a value to fields or use var if you would like to proceed with mutable structure, e.g.:
class Example {
val a: String = "example"
}
val example = new Example()
println(example.a)
Scatie: https://scastie.scala-lang.org/bQIcVNk9SN6qJhbL32SMUQ

Scala adding an extra function to a Class

I encountered the following code while checking through a Scala code. I'm finding it difficult to understand what it does.
class Foo(val name: String, val age: Int, val sex: Symbol)
object Foo {
def apply(name: String, age: Int, sex: Symbol) = new Foo(name, age, sex)
}
Does it add a constructor method to the Class Foo which was already defined?
Is it possible to add extra methods to classes which are already defined using this syntax?
Does it add a constructor method to the Class Foo which was already
defined?
It adds syntax sugar to the class. Meaning, you can create an instance of Foo like this:
val foo = Foo()
Instead of
val foo = new Foo()
Is it possible to add extra methods to classes which are already
defined using this syntax?
In that regards, apply is special as the compiler knows it and expands Foo() to Foo.apply. This means that any other method you want to invoke, you'll have to call the Foo static object, but they will not apply to the Foo instance.
If you want to externally add methods to Foo, you can do so via an implicit class:
implicit class RichFoo(foo: Foo) extends AnyVal {
def fooDetails(): String = s"{Name: ${foo.name}, Age: ${foo.Age}"
}
Now you can call it on an instance of Foo:
val f = Foo()
println(f.fooDetails())
In the case, you can think of Foo.apply() as a static method.
Realistically, objects in Scala are implemented as Singleton instances.
Here's the documentation on that.
You can invoke any class or object instance in Scala if it has an apply method. What you're doing here is adding a constructor method to Foo's companion object so that when you call it, it will instantiate an instance of Foo.
It is not possible to add methods to an instance with this method. For that, you might be interested in the Scala Pimp My Library pattern which is implemented using implicits.
// the following are equivalent, given your code above
val x = new Foo("Jason", 29, 'Male)
val y = Foo.apply("Jason", 29, 'Male)
val z = Foo("Jason", 29, 'Male)
Please read about companion object: http://docs.scala-lang.org/tutorials/tour/singleton-objects.html hope this helps
It simplifies object creation for this type. Other way will be to create case class.
Looks like as duplicate to me:
Scala: companion object purpose
This pattern is commonly know as static factory methods. The code you provided is not very useful, but consider these additional factory methods (think of them as "named constructors"):
class Foo(val name: String, val age: Int, val sex: Symbol)
object Foo {
def apply(name: String, age: Int, sex: Symbol) = new Foo(name, age, sex)
def newMaleFoo(name:String,age:int) = new Foo(name,age,'male)
def newPeterFoo(age:int) = new Foo("Peter",age,'male)
}

Scala pass-through wrappers

Very many times, I'll want to "replace" a single method of a given object.
foo: Foo
foo.bar(i) // original
foo.baz(s) // replace this implementation
I'll wind up creating a pass-through wrapper class.
class FooWrapper(foo: Foo) extends Foo {
def bar(i: Int) = foo.bar(i)
def baz(s: String) = foo.baz(s)
}
And then
foo: Foo
val foo2 = new FooWrapper(foo) { def baz(s: String) = ... }
foo2.bar(i)
foo2.baz(s)
This works with traits and classes, and works without modifying the source code of the type.
I use this quite a bit, particularly when adapting libraries or other bits of code.
This can get tedious with lots of methods. The other day, I wanted to replace the shutdown method on an ExecutorService instance, and I had to do this for a dozen methods.
Is this a common idiom, or is this normally done another way? I suspect this could be done nicely with a macro, though I haven't found any existing ones that do this.
You can achieve that with AOP (Aspect-oriented programming)
There're many libraries to do so, try this one -
https://github.com/adamw/scala-macro-aop
Note that this library is in POC stage for now so you might look for something more mature. I've put it here because I think it shows the concept very clearly.
For your example you'll have to do something like
class FooWrapper(#delegate wrapped: Foo) extends Foo {
def baz(i: Int) = ???
}

Constructor arguments are visible in entire class -- a feature or a bug?

Consider such code (this is just example not real code):
class Foo(url : String) extends Bar(url)
{
def say() { println(url) }
}
It compiles and it works. With nonsense results "of course". I am too newbie to judge, but for me it serves no purpose but confusion -- by definition it is impossible that the argument of the constructor could be reachable directly in another method.
Could someone more experience in Scala could point out condition when it might work or make sense? Or confirm my suspicion this is flaw in current Scala compiler.
Update
class Bar(val Url : String)
{
}
Why "nonsense". Because my will (no "var" and no "val" in Foo) was to just pass the argument, nothing else. So when I actually use the constructor argument it is just matter of what entity I use by mistake. When you write on purpose, you hit the jackpot each time, but if you don't (i.e. you make a mistake in spelling), you use entities by random. It is not the code does not make sense, it is the computation just does not make sense, I could roll a dice as well. There is a method scope, and I don't see a reason why there shouldn't be constructor scope.
Update -- workaround
So it seems this evil construct is really part of the language (by design). As UserUnknown and Tomasz Nurkiewicz suggested the only line of defense against making stupid typo is convention, however lower-upper case is not good. "A" and "a" differ a lot, but "U" and "u" not much. Introducing one special character (as Tomasz showed) is much better, because it is possible to visually detect fishy usage of constructor argument.
I will use "$" for "just-passing" constructor arguments, it is harder to type for me, and you don't see this character too often in the code.
Thank you for the answers!
Why it is evil? Because implicit actions should be allowed explicitly by users -- good examples are "dynamic" in C#, implicit conversions in Scala. And examples of breaking this rule which led to tons of problems are -- implicit conversions to bool in C++, implicit constructors in C++, declaration by usage in Perl. And this particular case is very, very close to the mentioned perlism, in Perl finally there was change in interpreter to detect such misusages, why Scala repeated the same mistake? I wonder.
Your suspicions are entirely merit-less. This is by design.
Parameters of a class are part of the class. They'll be preserved as field if necessary (such as in your example), or not if they are never used outside construction.
So, basically, if you don't need it as a field, it won't be. If you do, it will. And you'll never write a single extra character of code to tell the compiler what it can figure out by itself.
It's not a bug, it's a feature. In fact, a really nice one. Need an example how useful it is? Here is how I use it with Spring and dependency injection via constructor:
#Service
class Foo #Autowired() (bar: Bar, jdbcOperations: JdbcOperations) {
def serverTime() = bar.format(jdbcOperations.queryForObject("SELECT now()", classOf[Date]))
}
Equivalent code in Java:
#Service
public class Foo
{
private final Bar bar;
private final JdbcOperations jdbcOperations;
#Autowired
public Foo(Bar bar, JdbcOperations jdbcOperations)
{
this.bar = bar;
this.jdbcOperations = jdbcOperations;
}
public String serverTime()
{
return this.bar.format(this.jdbcOperations.queryForObject("SELECT now()", Date.class));
}
}
Still not convinced?
Short tutorial:
class Foo(var x: Int, val y: Int, z: Int) {
println(z)
//def zz = z
}
x will become a variable with getters and setter. y will become an immutable variable and z will become an immutable variable only if zz method is uncommented. Otherwise it will remain a constructor argument. Neat!
UPDATE: I see your point now! The following code works as expected by accessing url variable in base class:
class Bar(val url)
class Foo(_url : String) extends Bar(_url)
{
def say() { println(url) }
}
I agree, this is both ugly and is asking for trouble. In fact I once hit this problem myself when using Scala classes as Hibernate entities - I used constructor parameter instead of field in base class which caused duplicated field to be created: one in base class and one in derived class. I wouldn't even notice but Hibernate was screaming at runtime that duplicated column mapping was defined.
So I have to somewhat agree with you - this is somehow confusing and might be error-prone. This is the price you pay for "implicitness" and concise code.
However note that no modified and val modifier before constructor argument are different. Without modified immutable field is created, while val additionally adds getter.
Scala creates a field from a constructor parameter when such an parameter is referenced by a method in the class. I'm having trouble finding fault with the way that this works.
For the simple case everything works as expected:
scala> class Bar(val url: String)
defined class Bar
scala> class Foo(url: String) extends Bar(url) {
| def say() { println(url) }
| }
defined class Foo
scala> new Foo("urlvalue").say
urlvalue
If we introduce some confusion over the case of the constructor parameter this example still works as expected:
scala> class Bar(val Url: String)
defined class Bar
scala> class Foo(url: String) extends Bar(url) {
| def say() { println(url) }
| }
defined class Foo
scala> new Foo("urlvalue").say
urlvalue
Interestingly you might think that this has worked because it has introduced a lower-case url field in Foo in addition to the upper case Url in Bar, but that doesn't seem to be the case - the compiler seems to be smart enough to know that it can go to Url to get the value of url in say, as no lower case field is generated.
scala> :javap -private Bar
Compiled from "<console>"
public class Bar extends java.lang.Object implements scala.ScalaObject{
private final java.lang.String Url;
public java.lang.String Url();
public Bar(java.lang.String);
}
scala> :javap -private Foo
Compiled from "<console>"
public class Foo extends Bar implements scala.ScalaObject{
public void say();
public Foo(java.lang.String);
}
The only time I can see that this gets confusing is if you mis-spell a var field. In this case you do actually introduce a new field, and the two can get out of step.
scala> class Bar(var Url: String)
defined class Bar
scala> class Foo(url: String) extends Bar(url) {
| def say() { println(url) }
| }
defined class Foo
scala> val f = new Foo("urlvalue")
f: Foo = Foo#64fb7efa
scala> f.say
urlvalue
scala> f.Url = "newvalue"
f.Url: String = newvalue
scala> f.say
urlvalue
scala> :javap -private Foo
Compiled from "<console>"
public class Foo extends Bar implements scala.ScalaObject{
private final java.lang.String url;
public void say();
public Foo(java.lang.String);
}

How to define accessor method for default constructor parameter?

Trying to define an accessor method for default constructor parameter, i.e.:
class Person (age: Int) {
def age: Int = this.age
}
Which obviously results in a compiler error: ambiguous reference to overloaded definition, both method age in class Person of type => Int and value age in class Person of type Int match expected type Int
Is there a way in this context to distinguish between the member method name and auto-generated member value name?
Of course it's possible to change the name of either identifier, but is there a way in this scenario of actually specifying which identifier is referred to?
Just put "val" in front of constructor parameters that you want to expose as instance properties.
Use
class Person (val age: Int)
if you just want a getter or
class Person (var age: Int)
if you also want a setter.
The answers above are great wrt the uniform access principle. If you have or need Java style getters and setters you can also use the BeanProperty annotation.
class Person(#scala.reflect.BeanProperty var age: Int)
This will result in the following methods being created:
def getAge: Int = age
def setAge(age: Int) = this.age = age
If you instead use the BeanProperty for a val instead of a var, the setter won't be created, only the getter.
One other caveat, the setter method cannot be called from inside Scala. Instead, you should use the standard Scala convention of uniform access to set the value.
Just for completeness and to expand on the previous answers, there is also the technique covered here.
To summarize, I would always begin with an immutable value:
class Person (val age: Int)
Then, if you figure out you need to mutate the value (or you know it in advance), switch to:
class Person (var age: Int)
Then, if you need to validate or do some other computation on get or set, rename your variable and build accessors that mimic your original naming, no need to refactor the rest of the code:
class Person(var _age: Int)
{
def age =
{
println("age requested")
_age
}
def age_=(newAge: Int) =
{
assert(newAge > 0)
println(s"age changed from ${_age} to $newAge")
_age = newAge
}
}
Of course, you can simplify either setter or getter if you don't need operations there.
Kudos to all other answers, which are indeed correct and came much sooner.