what’s the cleanest/most kotlin-idiomatic way to d...
# announcements
a
what’s the cleanest/most kotlin-idiomatic way to define a method which can take one of 3 types of object, short of declaring 4x separate methods? The types in question are Date, String, Bool and Int. Wondered about a
sealed class
unsure if this is the most appropriate approach.
b
Overloading would be the cleanest approach
👍 2
t
Depends... if you define some sort of "algebra" the cleanest would be to do generic function and pass the "algebra" as additional parameter or receiver. Example: Mathematical Order is a algebra, that is represented in Kotlin by Comparator interface. Collection.sort function is sample method that receives this algebra.
sealed class / interface are idiomatic way for representing closed domains. I can't think of closed domain where Date, String, Bool and Int are only types that share the sematinc of such domain.
Overloading is the way to go if you just need to handle some common characteristic of those types internally in your implementation, but not in public API.
btw. Good topic for #C4GKV43N2
c
Depending on your requirements, Arrow Meta (#CJ699L62W) has union types, that can be used exactly for this. I don't remember how stable these are though.
👍 1
r
Imho this depends a lot on what exactly is the domain meaning of the attributes/functio - would have to specify thata bit more eg, those attributes could be all different formats of specifying a date - then you would want function to accept a single argument of type
X
, but could construct
X
with 3 different ways - either own
MyDate
class with 3 constructors or extension parser functions
Date.parse(String): Date
&
Date.parse(Int, Bool): Date
or it could be a function smth like
setJsonAttribute(name: String, value: ???)
- there it could be discussed between multiple overloads or
sealed class JsonValue
or maybe those union types pretty sure I could think up more variants with different results... 😄
d
I agree that with @Big Chungus, that overloading would be cleanest approach in most cases. Union types is way-to-go in such scenario, but not supported natively by kotlin. Arrow Meta requires extra plugin. I personally try to avoid adding extra things to build pipeline. But If I would be user of Arrow libraries already, I would try Union type plugin.
a
thanks everyone. I’ll start with method overrides I think.