Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm working on this thing that has some function callings like this:
fun f1(){
// does some stuff
f2();
}
fun f2(){
// does some stuff
f1();
}
This is a simplification of what my code looks like (it doesn't go for an infinity loop). My problem is that it returns the error that f2 is unreferenced. I tried searching this online but the only solutions I saw from people asking where to move the function above the funciton call, but that wouldn't work for me since my other function calls that one as well and moving the f2 above f1 would just make f1 unresolved when f1 is called from f2.
I also tried the function declaration thing c and c++ has but it lead to errors saying I have ambiguous function definitions and that they're expecting a function body in the function declaration.
Thanks.
I am assuming you are trying to define both functions inside the same local scope and getting an "Unresolved reference" Kotlin compiler error.
If that is your case and you cannot refactor your flow in a better way, then you can declare one of the functions as a nullable variable and assign it later.
Your code would then become
var f2: (() -> Unit)? = null
fun f1() {
// does some stuff
// Option 1: wont get invoked if f2 is null when this line is executed
f2?.invoke()
// Option 2: will always try to get invoked, but if f2 is null when this line is executed,
// it will throw a NullPointerException
f2!!.invoke()
}
f2 = {
// does some stuff
f1()
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
The sqlx extends the database/sql library and have Exec|Query function to run the pure sql without argument, but when i tried to run sqlx.Exec it said the sqlx have no Exec function. How to let sqlx run the pure sql method without any argument?
The github.com/jmoiron/sqlx is a package. Packages do not have methods, they may have functions.
Types may have methods. The sqlx.DB type is what you're looking for. It embeds the *sql.DB type which have a DB.Exec() method, which is promoted and is available on a value of type *sqlx.DB too.
So first you need an *sqlx.DB value, by connecting to the database, something like this:
db, err := sqlx.Connect("postgres", "user=foo dbname=bar sslmode=disable")
if err != nil {
log.Fatalln(err)
}
Here db is of type *sqlx.DB. Then you may use the Exec() method:
result, err := db.Exec("SELECT * FROM mytable")
This question already has answers here:
Example of when should we use run, let, apply, also and with on Kotlin
(6 answers)
Closed 3 years ago.
We can write the code with or without let as follows.
var str = "Hello World"
str.let { println("$it!!") }
OR
var str = "Hello World"
println("$str!!")
What is the Actual use of let?.Is that more memory efficient or more readable?
let is one of Kotlin's Scope functions which allow you to execute a code block within the context of an object. In this case the context object is str. There are five of them: let, run, with, apply, and also. Their usages range from but are not exclusive to initialization and mapping.
They are all very similar but they differ in terms of how the context object is referenced and the value that is returned. In the case of let the context object is referenced by the it keyword as opposed to the this keyword. The return value is whatever is returned from the lambda code block. Other scope functions like apply will return the context object instead.
Because let returns whatever the lambda block evaluates to, it is most suited to performing a mapping of some kind:
var upperStr = str.let { it.toUpperCase()}
apply is a more suited function for what you are doing.
To answer your question as to which code is more preferable, it really depends on what you are using the scope function for. In the above case there is no reason to use let. If you are using IntelliJ it will give a warning saying the call to let is redundant. Readability here is a matter of preference, and may be preferred.
The let function is useful when you wish to perform a null safe operation on an Object by using the the safe call operator ?. When doing this the let code block will only be executed if the object is not null. Another reason to use let is if you need to introduce new variables for the operation but you want to confine them to the scope of the let block. This is true for all scope functions, so I reiterate that let is best used for a mapping operation.
Edit: The let function should incur no additional cost. Normally we would expect the lambda/Code-block to be compiled to a Function object but this is not the case for an inline function in Kotlin for which the compiler will emit code not dissimilar to the second code example you have given. See the documentation for more information.
One of usages you can check nullable types
var str: String? = null
str?.let { println("$it!!") }
it's equal
if (str != null) {
System.out.println(str);
}
in Java, but shorter and more useful
let takes the object it is invoked upon as the parameter and returns the result of the lambda expression.
Kotlin let is a scoping function wherein the variables declared inside the expression cannot be used outside.
One of the examples would be here :
fun main(args: Array<String>) {
var str = "Hello World"
str.let { println("$it!!") }
println(str)
}
You can find more information on Kotlin let function here
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
So i started learning kotlin for android development.
But when i get to the visibility topic i met this note stating:
Local declarations
Local variables, functions and classes can not have visibility modifiers.
What are Local declarations in Kotlin ?
I asked you here witch means i already did a search on the internet but the only results i have got they were about java and other programming languages and i don't want to mix up things so i can avoid confusion.
Thanks very much in advance
Local declarations are declarations placed inside a body of a function (or a constructor, an init block, or a property accessor).
These declarations can only be referenced inside the lexical scope where they are declared:
fun foo() {
if (Random().nextInt() % 2 == 0) {
fun bar() {
println("bar")
}
bar() // OK
} else {
bar() // Error: unresolved reference
}
}
Consequently, these declarations can never be used outside the body, and therefore visibility modifiers (which normally control whether a declaration is accessible outside the type or the file) are meaningless for local declarations.
Local declarations can be used for entities that have meaning only inside a body of the function and not anywhere else, or should not be used anywhere else.
An example of a valid use case for local declarations is a data class for intermediate values of a calculation:
fun getAndSaveEmails(people: List<Person>) {
data class PersonWithEmail(
val person: Person,
val email: String
)
val peopleWithEmails = people.map { PersonWithEmail(it, requestEmail(it)) }
peopleWithEmails.forEach { save(it.person, it.email) }
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Here is sample
if (bar == null) {
// do something
}
vs.
bar ?: run {
// do something.
}
which one is best practice?
what is mutating property?
first one dosen't work with mutating property?
which one is best practice?
As pointed out by Oliver, the intent is most clear when using if(bar == null). This is also the approach used in official Kotlin documentation under Checking for null conditions.
Though I don't suggest it in this case, Kotlin allows you to do neat things like this:
inline fun whenNull(input: Any?, block: () -> Unit) {
if(input == null) block()
}
Which would allow you to rewrite if(bar == null) as:
whenNull(bar) {
// Do something
}
what is mutating property?
It's a variable whose value can be changed. Basically, the variable is declared using var and not val.
first one dosen't work with mutating property?
This isn't really relevant to your example because you are checking if(bar == null).
What you are referring to is relevant if you were checking if(bar != null). In this case, if bar is a var, Kotlin can't smart cast it a non-null type since within the body of the if the value of bar could change at any time. This means within the body of the if you'd have to make safe calls on bar (?.), or use !!.
You can work around this by doing the following:
val b = bar
if(b != null)
{
// b has been smart cast to a non-null type
}
Kotlin is able to smart cast b to a non-null type within the body of the if because it is non-mutable (val).
Alternatively, you can use a safe call and let, which calls the specified function/block with this value as its argument and returns its result. Given the safe call, this is of course non-null.
bar?.let {
// this is bar (non-null)
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
The community reviewed whether to reopen this question 10 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I recently implemented basic mechanics of a game of chess and used the Result<T, E> type for methods collecting human input, since it may be invalid. However, I'm not sure about what type I should pick for the possible error (E).
I have gathered that introducing new types is considered a good practice when building a library. However, when the Result can be handled immediately and the Err reported in stdout, isn't it simpler to just return Result<T, String>s or Result<T, &str>s (or Result<T, Cow<str>>s if both can occur)?
Consider the following case:
pub fn play() {
let mut game = Game::new();
loop {
match game.turn() {
Ok(()) => { game.turn += 1 }
Err(e) => println!("{}", e)
}
}
}
The game is played in the terminal and any input errors can immediately be reported. Is there any added value to introducing a custom error type in this case?
This is a rather broad question and there is no clear "right" or "wrong" answer.
It's important to note in your example, that strings carry very little easily accessible semantic information. Sure, you might be able to extract all semantic information by parsing the string, but this is really the wrong approach. Therefore, most bigger libraries or applications use error types that carry more semantic information to allow for easy error handling.
In your case, strings are probably fine, if you will print them immediately anyway. But there is a neat little trick in order to make at least the function signatures a bit more future proof: return Box<Error>.
The Error trait is a nice abstraction over errors. Pretty much every error type implements this trait. With the ? operator and the Into trait, it's possible to handle most errors with ease. Furthermore: there are a few type conversion impls for strings and Box<Error>. This allows to return strings as errors:
use std::error::Error;
fn foo() -> Result<(), Box<dyn Error>> {
std::fs::File::open("not-here")?; // io::Error
Err("oh noooo!")?; // &str
Err("I broke it :<".to_owned())?; // String
Err("nop".into())
}
fn main() {
println!("{}", foo().unwrap_err());
}
See the working demo.
Edit: please note, that Box<Error> carries less semantic information than another concrete error type like io::Error. So it's not a good idea to always return Box<Error>! It's just a better approach in your situation :)
Edit 2: I've read a lot on error handling models recently, which changed my opinion a bit. I still think this answer is pretty much true. However, I think it's by far not as easy as I formulated it here. So just keep in mind that this answer doesn't suit as general guide at all!