leosan
05/02/2018, 11:55 AM#SWIFT
enum NumberCategory {
case Small
case Medium
case Big
case Huge
init(number n: Int) {
if n < 10000 { self = .Small }
else if n < 1000000 { self = .Medium }
else if n < 100000000 { self = .Big }
else { self = .Huge }
}
}
How I can achieve something like this in kotlin?
Just to illustrate my problem I have a bunch of business logic conditionals that I want to convert to a type and send it to my view, I’m not even sure if this is the best solution or I stick with boolean methodsbenleggiero
05/03/2018, 2:53 AMenum class NumberCategory {
Small,
Medium,
Big,
Huge;
companion object {
operator fun invoke(n: Int) =
if (n < 10000) { Small }
else if (n < 1000000) { Medium }
else if (n < 100000000) { Big }
else { Huge }
}
}
elizarov
05/03/2018, 9:42 AMwhen
. And even more compliant to official Kotlin style if you use top-level constructor-like function named NumberCategory
instead of companion object
.benleggiero
05/07/2018, 2:10 AMelizarov
05/08/2018, 2:53 AMbenleggiero
05/08/2018, 3:31 AMoperator fun
is magic… Perhaps if it’s seen as such by the writers of stdlib, then it should be rethought. Perhaps we should allow factory-style constructorselizarov
05/08/2018, 12:28 PMoperator fun invoke
is a useful feature for certain DSL, but using it just to define a “factory function” requires too much syntax and boilerplate. A top-level function with the corresponding name solves the same problem simpler, more directly, with less code.benleggiero
05/08/2018, 12:30 PMelizarov
05/08/2018, 12:33 PMbenleggiero
05/08/2018, 12:36 PMelizarov
05/08/2018, 12:39 PMoperator fun invoke
was primarily designed for function-like objects and classes (all function types have it, for example). Using it on companion object
is clever hack, indeed, but understandable software should not be built using clever hacks.benleggiero
05/08/2018, 3:22 PMMyClass.Companion(arguments)
, but it's MyClass(arguments)