https://kotlinlang.org logo
Title
t

tipsy

09/29/2018, 6:46 PM
i'm looking for some help on how to simplify a concept i've been working on. currently i have a
Validator
class, which can be turned into a
TypedValidator
class by calling
asInt
,
asDouble
, etc: https://github.com/tipsy/javalin/blob/master/src/main/java/io/javalin/validation/Validator.kt the problem is that i have some duplicated functionality that i'd like to get rid of, but i can't think of any (simple) way of doing that
a

Andreas Sinz

09/29/2018, 8:24 PM
You want to de-duplicate those functions?
u

uli

09/29/2018, 8:26 PM
Doesn't asClass<Int> work?
t

tipsy

09/29/2018, 8:38 PM
yes @Andreas Sinz, that would be nice
a

Andreas Sinz

09/29/2018, 9:02 PM
@tipsy should
T::class.java
be limited to just a couple of types?
t

tipsy

09/29/2018, 10:12 PM
No, any type should be fine if you use asClass
u

uli

09/30/2018, 7:08 AM
Why do you need asInt? And if you need it, can't you define it as fun asInt = asClass<Int>
t

tipsy

09/30/2018, 8:04 AM
@uli you can't just cast strings directly, you need to register a converter for each (the API also has to work from java).
asInt()
,
asDouble()
etc are the most common types, which is why i've included them by default
if you need it, can't you define it as fun asInt = asClass<Int>
that i can do! thanks
a

Andreas Sinz

09/30/2018, 12:41 PM
@tipsy what is the difference between
asClass<Int>()
and
asInt() = asClass(Int::class.java)
? is the latter actually needed?
t

tipsy

09/30/2018, 1:17 PM
asInt()
is a lot easier to read and write than
asClass(Integer.class)
this is also being used from java
a

Andreas Sinz

09/30/2018, 1:40 PM
if you put java in the mix, yes. in a pure kotlin project
asClass<Int>()
is not much worse than
asInt()
t

tipsy

09/30/2018, 1:41 PM
java is in the mix, sorry ^^
i think i can make the
TypedValidator
a base class, i just haven't quite figured out how yet
got it, thanks to both of you!
a

andries.fc

10/17/2018, 7:34 AM
I would move all the
asClass<..>()
as extension functions. They are only there as an API, and the core of the functionality is implemented anyway in the
fun <T> asClass(clazz: Class<T>): TypedValidator<T>
.