Some variants come to my mind, but depending on how you use it later on, none might be suitable to you.
just use a default value, e.g.:
var port : Int = 8080
use some other Number
-type instead of Int
, e.g.
class Server {
lateinit var port : Number
}
You can then call port.toInt()
if you need to. But: there are a lot of Number
-types, so narrowing it down to e.g. BigInteger
might make sense. Otherwise you might get objects, you do not want to accept in the first place.
using Delegates.notNull
var port : Int by Delegates.notNull()
but: even though you spare your null
-value then, you can't check whether the variable has been initialized, so you just have to deal with an exception as soon as you want to access it... not very nice I think... but if you are sure you get a value, then that might be ok for you too.
just use Int?
and skip the lateinit
, e.g.:
class Server {
var port : Int? = null
}
Instead of ::port.isInitialized
you would ask for port != null
, but: you need to handle the possible null
-value now, but with ?
that shouldn't be such a big problem.
use Int?
with Delegates.vetoable
in case you do not want to accept null
-values after you got your first value, making it basically something like lateinit
;-)
class Server {
var port : Int? by Delegates.vetoable(null as Int?) {
_, _, newValue -> newValue != null
}
}
and check again using port != null
, which now behaves similar to ::port.isInitialized
Not that I am a big fan of the last two as they introduce null
again, but depending on what you do, that might be perfectly ok...
As you added something regarding String
concatenation, I would even more so use Int?
here. You can then still use something like:
url = "$host${port?.let { ":$it" }?:""}"
// or:
url = port?.let { "$host:$it" } ?: host
// or
url = listOfNotNull(host, port).joinToString(":")
The same can't be really easier with the ::port.isInitialized
?
Int?
was disallowed. - EpicPandaForceInt?
does not work. - mikebInt
and do not want a default value... or use some other type, e.g.BigInteger
? ;-) - Roland