29 Dec 18:32
Re: Scala Object Notation ( SCON? )
Jon Pretty <jon.pretty <at> sygneca.com>
2007-12-29 17:32:50 GMT
2007-12-29 17:32:50 GMT
Hi Andrés,
I understand that Scala's syntax isn't always as concise as JSON's (in
exchange for allowing you to do a whole lot more in general), though I
don't really understand your problems with anonymous subclassing.
Having said that, I think Martin's suggestion is a bit of a compromise
for the sake of conciseness, and I would prefer to write:
class Person {
def name : String
def age : Int
def foo = 42
}
val p = new Person {
def name = "Andres"
def age = 29
override def foo = 100
}
as this then guarantees that there's no risk of forgetting to initialize
any variables.
Andrés Testi wrote:
> 1) Subclassing breaks the encapsulation contracts allowing side
> effects. For example, the Person class have a protected var:
>
> class Person{
> var name: String = _
> protected var internalCode: Int = _
> }
>
> val p = new Person{
> name = "Andres" // Good
> internalCode = 123432 // DANGER!!!! I'just want to instantiate a
> class with the public vars
> }
I don't understand. Why is this dangerous? If 'internalCode' is
protected, then you have every right to do this, and no reason to
suspect that this shouldn't happen. Should 'internalCode' be private
instead?
I don't understand what you're saying about side-effects.
> 2) Hiding the owner scope:
>
> class Person{
> protected def op(a: Int) = a + 1
> }
>
> def op(a: Int) = a - 1
>
> val p = new Person{
> age = op(17) // WARNING!!!
> }
Shadowing is a fact of life, and it's certainly not unique to this
situation. In practice, you have to learn to give methods sensible and
unique names. If you practice this, you have to be quite unlucky to
have two different methods with the same name, the same signature, doing
different things occurring in a place where it's not obvious which one
is being referenced.
> 3) Anonymous class != Person class:
> (new Person).getClass != (new Person{name="Andres"}).getClass
This sort of code is a problem in general. If you expect to use
inheritance, you shouldn't be testing classes for equality. Use
(new Person { name = "Andres" }).isInstanceOf[Person]
instead.
> 4) This is just a function invocation
> new Person(name: "Andres", age: 29)
>
> this is a code secuence
> new Person{name = "Andres"; age = 29 }
Is this a problem, or just an observation?
Cheers,
Jon
--
--
Jon Pretty | Sygneca Ltd.
RSS Feed