Search code examples
rascal

Get string value out of a KeySym value


Is there a way to get the string value out of a KeySym value? For example, out of keyPrintable("a").


Solution

  • If you know the KeySym value is a keyPrintable, you can just get it using the key property. For instance

    KeySym kv = ... // something that yields a KeySym
    str s = kv.key;
    

    If you don't know it's a keyPrintable you can either check to see if it was built using that constructor, or use pattern matching. So, either

    if (kv is keyPrintable) {
      // code that uses kv.key to get back the value
    }
    

    or

    if (keyPrintable(str s) := kv) {
      // code that can now use s, which is the key
    }
    

    You can also ask if kv has that field, and then use it:

    if (kv has key) {
      // code that uses kv.key
    }
    

    Once you introduce a field name in a constructor, and it has a specific type, you know that same field name has that same type in any additional constructors for the same datatype. So, once we know field key is type str, field key has to be str in any value of type KeySym. That is why it's fine to see if kv has field key and then treat it as a str, nobody could come along later and add a new constructor for KeySym where key has a different type.