Json models with null safety -> ugly code


#1

Working with json we expected json from server and we should describe models:

class Bean(){
  var title:String? = “”
  var author:String? = “”
  …
  var otherParmas = “”
}
assume of hundreds varialbles

I don’t want to set default not null value to params, It is requere more time, code become to complicated and not nice.

I would like only to declare bean:

class Bean(){
  var title:String
  var author:String
  var p1:Int
  var p2:Int   
}
Why don’t Kotlin compiler set default value for general type: “” for String and 0 for Int ?

What do you think about it?


#2

There's more danger in defaults that value. BTW, you can say what you want like this:

class Bean(){   var title:String = "",   var author:String = "",   var p1:Int = 0,   var p2:Int = 0 }

I don't see much of a problem here


#3

Is there a way that nullability can be defined for a variable of which the type is inferred? I tried some things, but nothing compiled:

open class Foo() {   var str = "" // var str? = "" or something does not compile

  fun bar() {
  str = null  // Null cannot be a value of a non-null type jet.String
  }
}


#4

I see only two ways: 1. Specify type explicitly 2. Write a function

fun <T: Any> T.nullable(): T? = this

and say

var s = “”.nullable()


#5

I like the nullable() method: simple and short ;-) If I get it right when the dot operator has been fully implemented it should be possible to say: var s = ""?