开发者

Best way to know if something isBoolean

What's the best way to ask an object whether it's a boolean?

As requested, here's the reasons:

I开发者_如何学编程've a method that prints stuff, any kind of stuff, and when this stuff is a boolean I want it to print 'Yes' or 'No' instead of true or false. I was doing it like this, but it looked too much as a hack to me:

[anObject
    ifTrue: [ 'Yes' ]
    ifFalse: [ 'No' ] ] 
        on: Error 
        do: [ anObject printString ]


Add your own definition of printString then:

Object >> #bernatPrintString
  ^self printString

True >> #bernatPrintString
  ^'Yes'

False >> #bernatPrintString
  ^'No'


anObject == true or: [ anObject == false ]


value isKindOf: Boolean – but I would avoid such checks! Probably there's something a bit wrong if you need to do this...


What could be simpler?

anObject isBoolean ifTrue: [ ... ] ifFalse: [ ... ]


Even simpler, most efficient and not need to avoid: value class == Boolean

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜