https://kotlinlang.org logo
#announcements
Title
# announcements
j

Joaquim Ley

08/10/2019, 4:30 PM
Hello Anyone has exp with moshi when dealing with different types on the same property? My specific use case, I have a variable that sometimes returns an object and others a boolean 🤷‍♂️ I know this must be done with adapters but I haven’t been able to get it to work, since all the examples I read is from a int to bool or something like that, not primitive to object Thanks in advance 💪 ```
d

Dominaezzz

08/10/2019, 4:33 PM
Code example? (Have you considered
kotlinx.serialisation
😛).
k

kevindmoore

08/10/2019, 4:33 PM
When using GSON, we just have 2 different nullable variables for each case. Not the best, but it worked
j

Joaquim Ley

08/10/2019, 4:35 PM
Copy code
object: {
  owner: "John Doe",
  price: false <--------- bool
},

(...)

object: {
  owner: "John Doe",
  price: { <--------- Object
      rate: 0.00420529425481,
      amount: 343
  }
},

(...)
Here’s a small snippet to illustrate the use case, regarding kotlinx I haven’t used it as an adapter for retrofit so not sure if it is working, as for GSON it would a big change and possibly loose capability of the default values 😄
k

kevindmoore

08/10/2019, 4:38 PM
I wanted to switch to Moshi but co-worker didn't want to change
d

Dominaezzz

08/10/2019, 4:39 PM
Well, this looks like sealed class territory.
k

kevindmoore

08/10/2019, 4:40 PM
j

Joaquim Ley

08/10/2019, 4:42 PM
I’ve read, and re-read that article still haven’t been able to figure out,t his has to do with the Kotlin adapter which I’m unable to build a working solutions :S @Dominaezzz don’t really get where sealed classes would be useful here?
d

Dominaezzz

08/10/2019, 4:43 PM
What type do you want
price
to be?
j

Joaquim Ley

08/10/2019, 4:45 PM
the object… and null if bool
d

Dominaezzz

08/10/2019, 4:46 PM
Oh! Instead of using
null
,
false
is used.
I didn't understand that.
You can make a type adapter and check for
"false"
.
j

Joaquim Ley

08/10/2019, 5:04 PM
Thanks for your input but that’s exactly what I’ve been saying, if you read what I’ve said you can see what my use case is, I don’t get the sealed classes and checking for “false” would help. My issue is exactly with the adapter from boolean to object (the one I specify), I’ve been searching all over the interwebz and can’t seem to find a good solution :S
k

kevindmoore

08/10/2019, 5:08 PM
I think what Dominic is saying is that by using a sealed class with a name of "price", you could have 2 different types: One that has a boolean value and another that has the items in your object
👌 1
d

Dominaezzz

08/10/2019, 5:08 PM
Copy code
class PriceAdapter(val adapter: RealPriceAdpater) {
  @ToJson fun toJson(price: Price?): String {
    return if (price != null) adapter.toJson(price) else "false"
  }

  @FromJson fun fromJson(price: String): Price? {
    if (price == "false") return null
    return adapter.fromJson(price)
  }
}
🙏 1