Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 426 Vote(s) - 3.56 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I initialize a final field in Kotlin?

#1
Let's say I declared a final field with `private final String s` (Java) or `val s` (Kotlin). During initialization I want to initialize the field with the result of a call to a remote service. In Java I would be able to initialize it in the constructor (e.g. `s = RemoteService.result()`), but in Kotlin I can't figure out how to do that because as far as I can tell the field has to be initialized in the same line it's declared. What's the solution here?
Reply

#2
You can set `val` value in init block:

class MyClass {

val s: String

init {
s = "value"
}

}
Reply

#3
You can also initialize the value with [`by lazy`](

[To see links please register here]

) the value will be initialized the first time it is referred. An example

val s by lazy { RemoteService.result() }

kotlin will guess the type of s from the return type of the expression.
Reply

#4
It has been possible to do it simply like this since the very first official stable release of Kotlin:

class MyClass {
val s = RemoteService.result()
}
Reply

#5
You can use [`run`][1]:

class MyClazz {
val prop = run {
// do stuff
// do stuff again
123 // return expression
}
}

From the [docs][1] (emphasis is mine):

> Besides calling `run` on a receiver object, you can use it as a non-extension function. ***Non-extension `run` lets you execute a block of several statements where an expression is required.***


[1]:

[To see links please register here]

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through