Loading...

Friday, November 13, 2009

Groovy Goodness: Convert String to Boolean

Groovy adds the toBoolean() method to the String class. If the value of the string is true, 1 or y the result is true, otherwise it is false.

assert "y".toBoolean()
assert 'TRUE'.toBoolean()
assert '  trUe  '.toBoolean()
assert " y".toBoolean()
assert "1".toBoolean()

assert ! 'other'.toBoolean()
assert ! '0'.toBoolean()
assert ! 'no'.toBoolean()
assert ! '  FalSe'.toBoolean()

3 comments:

kdorff said...

My "boolean" values often comes from grails form postings (checkboxes) and the values can be null. "True" values (checked) come back as "on" which, is a bit odd. So my boolean conversion is

def obtainBoolean(value) {
  if (value == null) return false
  final String b = "$value".trim().toLowerCase()
  return b == "t" || b == "true" || b == "y" || b == "yes" || b == "on" || b == "1"
}

Andrey Paramonov said...

GPathResult also has toBoolean() method, which allows you to parse boolean attributes and elements:

def xmlStr = """
    <xml true-attr=" tRUe " y-attr="Y " one-attr=" 1" false-attr=" FALSE " n-attr="N" zero-attr="0">

        <true-elem>True</true-elem>
        <y-elem> y </y-elem>
        <one-elem> 1 </one-elem>

        <false-elem>false</false-elem>
        <n-elem> n </n-elem>
        <zero-elem> 0 </zero-elem>
    </xml>
"""
def xml = new XmlSlurper().parseText(xmlStr)

assert xml.@"true-attr".toBoolean()
assert xml.@"y-attr".toBoolean()
assert xml.@"one-attr".toBoolean()

assert ! xml.@"false-attr".toBoolean()
assert ! xml.@"n-attr".toBoolean()
assert ! xml.@"zero-attr".toBoolean()

assert xml."true-elem".toBoolean()
assert xml."y-elem".toBoolean()
assert xml."one-elem".toBoolean()

assert ! xml."false-elem".toBoolean()
assert ! xml."n-elem".toBoolean()
assert ! xml."zero-elem".toBoolean()

mrhaki said...

@Andrey Paramonov: I didn't know that. Thank you for contributing this information.

Post a Comment