What is the idiomatic way to determine the type of enum in Smalltalk?

Like in Java, C #, etc. How would I define something like enum Direction { input, output }in Smalltalk?

+4
source share
4 answers

Trivial approach

The most trivial approach is for class methods to return characters or other underlying objects (such as integers).

So you can write your example as follows:

Direction class>>input
    ^ #input

Direction class>>output
    ^ #output

And use:

Direction input

The main disadvantages:

  • any other "enumeration" that returns the same value is equal to this, even if the enums are different (you can return, for example ^ self name + '::input')
  • , (Uh... 7?)

enum .

:

  • = hash, enum - ()
  • printOn:

.

Object subclass: #DirectionEnum
    slots: { #value }
    classVariables: {  }
    category: 'DirectionEnum'

"enum accessors"
DirectionEnum class>>input
    ^ self new value: #input

DirectionEnum class>>output
    ^ self new value: #output

"getter/setters"
DirectionEnum>>value
    ^ value

DirectionEnum>>value: aValue
    value := aValue

"comparing"
DirectionEnum>>= anEnum
    ^ self class = anEnum class and: [ self value = anEnum value ]

DirectionEnum>>hash
    ^ self class hash bitXor: self value hash

"printing"
DirectionEnum>>printOn: aStream
    super printOn: aStream.
    aStream << '(' << self value asString << ')'

Direction input.
DirectionEnum output asString. "'a DirectionEnum(output)'"

, , .

, , . , Enum, DirectionEnum .

+4

Smalltalk SharedPool (a.k.a. PoolDictionary). , , , Java Smalltalk, SharedPool. :

key value .

PoolDictionaries , Pharo SharedPool. Pharo . ().

, SharedPool ColorConstants 'Red', 'Green', 'Blue', 'Black', 'White' .., :

SharedPool
  subclass: #ColorConstants
  instanceVariableNames: ''
  classVariableNames: 'Red Green Blue Black White'
  poolDictionaries: ''
  package: 'MyPackage'

, :

ColorConstants class >> initialize
  Red := Color r: 1 g: 0 b: 0.
  Green := Color r: 0 g: 1 b: 0.
  Blue := Color r: 0 g: 0 b: 1.
  Black := Color r: 0 g: 0 b: 0.
  White := Color r: 1 g: 1 b: 1.
  "and so on..."

ColorConstants initialize

Object
  subclass: #MyClass
  instanceVariableNames: 'blah'
  classVariableNames: ''
  poolDictionaries: 'ColorConstants'
  package: 'MyPackage'

MyClass ( ) :

MyClass >> displayError: aString
   self display: aString foreground: Red background: White

MyClass >> displayOk: aString
   self display: aString foreground: Green background: Black
+3

Smalltalk , , , .

: . . , , . direction := #input. direction := #output

+2

, , - IdentityDictionary.

, Java ( , , , ..), , , . ( , -, ), , , , , .

+2

Source: https://habr.com/ru/post/1695244/


All Articles