Groovy web console

subscribe to the feed Subscribe
to this
site
Enums in Groovy (via #groovywebconsole)
tweet this snippet Tweet
this
script

Enums in Groovy

Published 3 weeks ago by Luis G. Epifanio with tags Enums
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import java.lang.IllegalArgumentException

enum T {
    KEY1('key1'),
    KEY2('key2'),
    DEFAULT('')
    
    final String valor
    
    T(String val){ valor = val }
    static fromName(String val){
        values().find{ it.name() == val } ?: DEFAULT
    }
}

assert ( 'KEY1' as T ) instanceof T

try { 
    'SARLANGA' as T
    assert false
} catch (all) { 
    assert true 
}
assert 'KEY1' in T.values()*.name()  == true

assert T.fromName('SARLANGA') == T.DEFAULT
assert T.fromName('KEY1') == T. KEY1