Q: Test item type of a container in kotlin I'm trying to write some Kotlin wrapper around Android SharedPreferences and I'm having this code right now:
class KPreferences(ctx: Context) {
    val prefs = ctx.getSharedPreferences(ctx.getString(R.string.app_name), Context.MODE_PRIVATE)

    fun put(key: String, value: Any): Boolean {
        val editor = prefs.edit()
        when (value) {
            is Boolean -> editor.putBoolean(key, value)
            is Float -> editor.putFloat(key, value)
            is Int -> editor.putInt(key, value)
            is Long -> editor.putLong(key, value)
            is String -> editor.putString(key, value)
            is Set<*> -> editor.putStringSet(key, value as Set<String>)
        }
        return editor.commit()
    }

This compiles but I can't help searching if I can't make this better by being sure that the Set contains only String and no other type.
I tried this:
fun put(key: String, value: Any): Boolean {
        val editor = prefs.edit()
        when (value) {
            is Boolean -> editor.putBoolean(key, value)
            is Float -> editor.putFloat(key, value)
            is Int -> editor.putInt(key, value)
            is Long -> editor.putLong(key, value)
            is String -> editor.putString(key, value)
            is Set<*> ->
                if (value.isEmpty() || value.iterator().next() is String) {
                    editor.putStringSet(key, value as Set<String>)
                }
        }
        return editor.commit()
    }

But it seems so inelegant.
The other approach would be defining
fun put(key: String, value: Set<String>)

and remove the last case in my attempt. I'm just wondering if I'm missing any elegant solution here.
Thanks!

A: First, I'd like to note that the check you have in the example may not guarantee you from putting a set of something other than string into your editor: if the editor implementation does not copy the set upon putting it, one could pass in an empty set and then later add something other than a string to it:
val set = HashSet<Int>()
prefs.put("...", set) // set is empty, the check lets it through
set.add(1)

Generic type information is not reified, so you'll need to either introduce overloads for every type you support: Boolean, Float etc, and Set<String>, or go for no proper checking at all

A: I've already made a similar library and it's stable. You can use it if you want: KPreferences
It uses a completely similar approach.
