Reputation: 11137
Sorry for the newbie question. Is there an equivalent scala idiom to Python code where I can test for a value of different types?
if value in ['true', True, "1", 1]:
ret_value = True
elif value in ['false', False, "0", 0]:
ret_value = False
Upvotes: 2
Views: 67
Reputation: 16324
Idiomatic Scala generally avoids variables that can be of any type, and so most Scala programmers would avoid this situation. It does come up once in a while, though. You could do:
val truthies = Set(true, 1, "1", "true") // Set[Any], a type that would generally be avoided
truthies("true") //true
truthies(1) //true
truthies("foo") //false
Upvotes: 2
Reputation: 5999
I don't think so. It would not make a lot of sense, since your value
variable has a fixed type. As such, 3 out of your 4 possible values will never work, and the compiler knows it.
That said, if you have a set of possible values of the same type, you can always use List(1, 2, 3, 4).contains(value)
The real beauty of a strongly typed language is that it make a whole category of errors impossible! So you don't need to code that defensively.
Upvotes: 2