Skip to content

Instantly share code, notes, and snippets.

@ilya-g
Last active November 3, 2016 05:26
Show Gist options
  • Save ilya-g/f38d1855a872858101ac842cb6ca134d to your computer and use it in GitHub Desktop.
Save ilya-g/f38d1855a872858101ac842cb6ca134d to your computer and use it in GitHub Desktop.
In order not to instantiate singletons with gson
import com.google.gson.*
fun <T : Any> GsonBuilder.registerSingletonInstance(instance: T): GsonBuilder =
registerTypeAdapter(instance.javaClass, InstanceCreator { instance })
fun main(args: Array<String>) {
// val gsonBuilder = GsonBuilder().registerTypeAdapterFactory(object : TypeAdapterFactory {
// override fun <T: Any> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? {
// val c: Class<T> = type.rawType as Class<T>
// return c.kotlin.objectInstance?.let { instance ->
// object : TypeAdapter<T>() {
// override fun read(`in`: JsonReader): T {
// `in`.beginObject()
// `in`.endObject()
// return instance
// }
//
// override fun write(out: JsonWriter, value: T) {
// out.beginObject()
// out.endObject()
// }
// }
// }
// }
// })
val gson = GsonBuilder().registerSingletonInstance(Unit).create()
val u1 = Unit
val u2 = gson.fromJson("{}", Unit::class.java)
val u3 = Unit
println(u1 == u2)
println(u1 == u3)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment