Scala python equivalent __getattr __ / __ setattr__

Is there a scala equivalent of python __getattr__ / __setattr__(and other methods __*__?). Are some things built-in or maybe some features?

+3
source share
2 answers

For __getattr__and __setattr__you will have to wait while someone with a deeper understanding describes the new Scala 2.10 API. (And, of course, it will not be directly translated ever. It depends entirely on your use case. If you just want a dynamic class, there will be a Dynamicsign in the future , and if you just want it a little, then designing around pattern matching may be an obvious choice.)

__*__ Python:

  • __call__apply()//
  • __metaclass__// :
    • class trait mixins
    • , , , super(); Scala super() .
  • __repr__, __str__toString()
  • __eq__equals()
  • __init__//
  • __new__// ;
  • __del__//
  • __nonzero__// , implicit def toBool[MyType](a: MyType): Boolean = ...

  • __len__length, size -
  • __getitem__apply(i: IndexType)// - Scala
  • __setitem__update(i: IndexType, v: ValueType)
  • __delitem__// ;
  • __iter__foreach(block: ValueType => Unit)// : map, flatMap

, apply update Scala, Python. :

val x = collection(elem) // val x = collection.apply(elem)
collection(elem) = y // collection.update(elem, y)

, Pythons __iter__ (el for el in container) foreach map, for (el <- container) yield el.

, , :

  • __add__, __sub__,...// def + (arg: T) def - (arg: T)

  • __lt__, __ge__def <(other: T), def <=(other: T)

, Python, :

  • __radd__, __rsub__,...//- ; . def +: (arg: T) def -: (arg: T) ( :)
  • __iadd__, __isub__,...// : def += (arg: T),...

  • __enter__, __exit__//

: Scala 's magic "

+11

, . Scala , "" , "" Scala .

, :

var x: Int = 0

private[this] var _x = 0
def x = _x
def x_=(n: Int) { _x = n }

getter setter .

, , , , . 2.9.2, 2.10, , ( , , , ).

+2

All Articles