How can I force function parameters onto new lines? - kotlinpoet

I want all function parameters to be generated on a new line, like so:
fun test(
a: Int,
b: Int,
c: Int
)
How can I do this? At the moment the parameter lists wrap arbitrarily. I have an unknown number of function parameters to generate.

Right now, if the function has more than 2 parameters, each parameter will appear on a new line, otherwise the function signature will be printed on a single line. We don't provide APIs for modifying this behavior.

Related

Why Are My Tables Returning NIL and Not Populating?

I'm new to Lua and trying to understand the concept of OOP in Lua. To do so, I've tried creating an object and creating methods and "private variables". My issue is when I try to use "setters" or "getters", it's indicating that my tables are returning NIL which means I'm either having a scoping issue or something else I can't figure out.
The kicker is I'm using an example from an online Lua coding tutorial, and when I run the tutorial it works flawlessly. However, when I run mine, I get NIL or nothing outputs whenever I try to "get" or return a value from one of the member functions.
I'm using a couple of different environments:
ZeroBrain
Sublime Text
Lua for Windows
Do you know why my code is not returning populated tables?
newPlayer = function(n, h, a, r)
player = {}
n = n or ""
h = h or 100
a = a or 100
r = r or 0
function player:getPlayerName()
return n
end
function player:getPlayerHealth()
return h
end
function player:getPlayerArmor()
return a
end
function player:getPlayerRank()
return r
end
function player:setPlayerName(arg)
n = arg
end
function player:setPlayerHealth(arg)
h = arg
end
function player:setPlayerArmor(arg)
a = arg
end
function player:setPlayerRank(arg)
r = arg
end
function player:connect(arg)
print(string.format(" %s joined" , arg))
end
return player
end
player1 = newPlayer("John", 100, 100, 1000)
player1.getPlayerName()
Your code does not contain "populated tables" to return.
Your newPlayer function does create a table, and it does return it. It creates a number of functions within that table. But that's all newPlayer does: creates a table and puts some functions in it.
The data accessed by those functions is not part of the table. n, h, a, and r (BTW, please use better variable names) are all local variables. Your inner functions will access the specific stack containing those variables, but the variables themselves will not be magically associated with the table.
Your principle problem is almost certainly with the setters. And it comes from a combination of this:
function player:setPlayerName(arg)
with this:
player1.getPlayerName()
When you create a function using a : character between a table name and the function's name, you are using syntactic sugar for a function which implicitly takes as its first argument a value called self. As the name suggests, this is supposed to represent the object which this function is being called upon. So your function creation code is equivalent to:
function player.setPlayerName(self, arg)
Since you create all of your functions with :, all of your functions take at least one parameter.
The : syntax can also be used when calling such functions. If you did player1:getPlayerName(), this would cause the table you accessed to find the getPlayerName function to be used as the first argument in the function call. So that line would be equivalent to player1.getPlayerName(player1).
Obviously, these two syntaxes are mirrors of one another: functions created with : take a parameter that is expected to refer to the table it is being called on, and functions called with : will be given the table which was accessed to get that function.
But... your code didn't stick to the symmetry. You created the functions with :, but you call them with .
Now, you get functions are able to get away with this because... well, none of your values are actually part of the table. So your get functions just return the local value that they adopted from their creating context.
The set functions pose a problem. See, they take a parameter. But because the function was declared with :, they really take two parameters, the first being the implicit self.
Now, : syntax is just syntactic sugar; it's just a convenient way to do what you could have done yourself. So it is in theory OK to call a function with . even if you created it with :. But if you do so, you must pass the table as the first parameter. Though your code doesn't show it, I strongly suspect you didn't do that.
If you called player1.setPlayerName("foo"), what will happen is that the implicit self parameter will get the value "foo", and the arg parameter will be nil. And you will assign that nil value to the n local variable. So subsequent calls to player1.getPlayerName() will return nil.
Basically, what's going on here is that you're combining two different ways of creating objects in Lua. You stored your private data in a way that external code cannot access (ie: local upvalues), but that data is now no longer part of the table itself. Which means that, although you dutifully create those functions with : syntax to indicate that they take a self table, they never actually use that table. And because they never use the table, it's a lot harder to figure out what's going wrong.
Basically, the key here is to be symmetrical. If you create a function with :, then you should either call it with : or make sure to pass it the object table as the first parameter.
Broadly speaking, the standard way to create private members is by convention, not by forbidding it. That is, you agree not to mess with any members of a table other than those with certain names. Python convention is to pretend that names starting with _ don't exist, and Lua programs sometimes use that.
Upvalues are an interesting solution for private variables, but they do come with problems. If you want to invent a member variable, you have to do it in a centralized place rather than wherever you might need one. Even if the variable is optional, you have to create a named local at the top of the function.
TLDR of Nicol's answer, see my answer to another question:
function player:setPlayerArmor(arg)
a = arg
end
The : syntax is syntactic sugar. It creates an implicit 'self' argument when declared, and when used. If you declare it one way and use it another, the arguments won't be what you're expecting. Say your player has 100 health. Look at this result:
player1.setPlayerHealth(55, 66)
print(player1.getPlayerHealth())
-- will display '66', not '55' because `:` declares implicit 'self' argument
This displays 66 because the setPlayerHealth function has an implicit 'self' parameter because it was declared with :. If you instead called it
with the ::
player1:setPlayerHealth(55, 66)
print(player1:getPlayerHealth())
-- will display '55' because `:` passes player1 as self
function player:setHealth1(arg)
-- implicit 'self' argument refers to player1 when called on player1
end
-- is the same as
function player.setHealth2(self, arg)
-- with `.` notation, you need to add the 'self' argument explicitly
end
player1.setHealth1(31) -- self argument will be 31 and arg will be nil
player1.setHealth2(32) -- self argument will be 32 and arg will be nil
player1:setHealth1(33) -- self argument will be player1 and arg will be 33
player1:setHealth2(34) -- self argument will be player1 and arg will be 34

Could someone, please, explain me the implementation of the following "Kotlin Literal high order function"?

I am a newbie in Kotlin, I just started to learn it,
I get the following code example about literal/high order function:
fun myHigherOrderFun(functionArg: (Int)->String) = functionArg(5)
println ( myHigherOrderFun { "The Number is $it" })
prints "The Number is 5"
Which I have difficulty to understand: the function myHigherOrderFun get a lambda function as parameter but i can't understand, where is the (Int) input parameter? I see is passed in functionArg(5)... but i can't realize how is possible that?
Thanks in advance.
To start from the beginning, in Kotlin functions are first-class types, just like numbers and Strings and stuff.  So a function can take another function as a parameter, and/or return a function as its result.  A function which does this is called a ‘higher-order function’.
And that's what you have in your example!  The line:
fun myHigherOrderFun(functionArg: (Int)->String) = functionArg(5)
defines myHigherOrderFun() as a function which takes one parameter, which is itself a function taking a single Int parameter and returning a String.  (myHigherOrderFun() doesn't specify an explicit return type, so it's inferred to be a String too.)
The next line is probably where things are less clear:
println(myHigherOrderFun{ "The Number is $it" })
The first non-obvious thing is that it's calling myHigherOrderFun() with a parameter.  Because that parameter is a lambda, Kotlin lets you omit the usual (…), and use only the braces.
The other non-obvious thing is the lambda itself: { "The Number is $it" }. This is a literal function taking one parameter (of unspecified type).
Normally, you'd have to specify any parameters explicitly, e.g.: { a: Char, b: Int -> /* … */ }.  But if there's exactly one parameter, and you aren't specifying its type, then you can skip that and just refer to the parameter as it.  That's what's happening here.
(If the lambda didn't reference it, then it would be a function taking no parameters at all.)
And because the lambda is being passed to something expecting a function taking an Int parameter, Kotlin knows that it must be an Int, which is why we can get away without specifying that.
So, Kotlin passes that lambda to the myHigherOrderFun(), which executes the lambda, passing 5 as it.  That interpolates it into a string, which it returns as the argument to println().
Many lambdas take a single parameter, so it gets used quite a lot in Kotlin; it's more concise (and usually more readable) than the alternative.  See the docs for more info.

Extension function on a generic type

I am new in Kotlin and I am trying to understand type alias and functions.
I have the following example:
interface EmptyInterface
typealias GenericCase<T> = T.(EmptyInterface) -> T
val myFunctionVariable: GenericCase<String> = {
_ -> "Hello world!"
}
So far what I understand is that I extend what ever T is defined with a function that accepts as argument an EmptyInterface and returns a T.
So the myFunctionVariable is a function that should be called passing an EmptyInterface
But the following code does not compile
class a: EmptyInterface
println("${myFunctionVariable(a())}")
I need to pass a String as the first parameter:
class a: EmptyInterface
println("${myFunctionVariable("",a())}")
Why is the string needed as the first parameter? T.(EmptyInterface) -> T which in this case is String.(EmptyInterface) -> String has only 1 parameter.
Could someone please explain this?
The T. in the type T.(EmptyInterface) -> T means that this function is an extension function on T. So the regular way to call this function is to acquire a T instance, and call it on that instance, as if it was a member function. In the case of your example, where you chose T to be a String, you have to call the function on a String instance:
"foo".myFunctionVariable(a())
The syntax you've used is an alternative way to call this extension, passing in the receiver as if it was the first parameter of the function (which, at the bytecode level, it actually is):
myFunctionVariable("foo", a())
If you wish to use your function with this syntax, however, it's better to declare it to take two parameters, as this invocation of an extension function can be quite unexpected.
(There's some more info about how you can go back and forth between a function that's an extension on a type and one that takes it as a first parameter in this answer.
In the type T.(EmptyInterface) -> T, the first T is the receiver: an instance that the function is called upon, and which becomes this within the function definition.  (Similar to an extension function.)
Effectively, the receiver becomes a hidden first parameter to the function; as you discovered, if you try to call the function directly, you'll need to give it explicitly.
The language spec for it is here; some other answers may also help.

Kotlin: how to make a function call using the first argument's default value and passing a value for the second?

I'd like to know how to call a function with default arguments when you want to specify the value of the second argument. In the simple example below I am showing that the addTwo() takes two arguments. The 'first' argument has a default value but the 'second does not. How would I call this function specifying that I want to use the default value for 'first' with the given value of 2 for 'second'?
Calling addTwo(2) throws an error.
fun main(args: Array<String>) {
var sum = addTwo(1,2) // works fine
var nextSum = addTwo(2) // ERROR: No value passed for parameter second
}
fun addTwo(first: Int = 0, second: Int): Int {
return first + second
}
This is an error because Kotlin does not know why you omitted a second parameter. The first can be defaulted, but not second. Therefore when you only passed in one argument it was for parameter first. The error message says exactly what the problem is:
no value passed for parameter second
You must call using named arguments for anything after the first defaulted parameter that you want to leave blank. For your case, this would be:
addTwo(second = 2) // first defaulted to 0
Had your defaulted parameters been in the other order, your call would be fine.
fun addTwo(first: Int, second: Int = 0): Int{
return first + second
}
addTow(2) // no error, second defaulted to 0
Had your data types been different for the two parameters, you would have seen a different less clear error letting you know the type of the first parameter (Int) was expected, not the type of the second (Date in the following example):
fun something(first: Int = 0, second: Date): Date { ... }
something(Date()) // ERROR: Type mismatch: inferred type is java.util.Date but kotlin.Int was expected
Note: You can run into the same issue with vararg:
Only one parameter may be marked as vararg. If a vararg parameter is not the last one in the list, values for the following parameters can be passed using the named argument syntax
Additional note: because of what you experienced, it is generally a best practice to make default arguments the last parameters in the list. Some languages even force this, such as Python (except that Python allows forced named arguments after defaults, since forcong you to call them by name is how you'd get around having parameters after default arguments anyway).

What is "_," (underscore comma) in a Go declaration?

And I can't seem to understand this kind of variable declaration:
_, prs := m["example"]
What exactly is "_," doing and why have they declared a variable like this instead of
prs := m["example"]
(I found it as part of Go by Example: Maps)
It avoids having to declare all the variables for the returns values.
It is called the blank identifier.
As in:
_, y, _ := coord(p) // coord() returns three values; only interested in y coordinate
That way, you don't have to declare a variable you won't use: Go would not allow it. Instead, use '_' to ignore said variable.
(the other '_' use case is for import)
Since it discards the return value, it is helpful when you want to check only one of the returned values, as in "How to test key existence in a map?" shown in "Effective Go, map":
_, present := timeZone[tz]
To test for presence in the map without worrying about the actual value, you can use the blank identifier, a simple underscore (_).
The blank identifier can be assigned or declared with any value of any type, with the value discarded harmlessly.
For testing presence in a map, use the blank identifier in place of the usual variable for the value.
As Jsor adds in the comments:
"generally accepted standard" is to call the membership test variables "ok" (same for checking if a channel read was valid or not)
That allows you to combine it with test:
if _, err := os.Stat(path); os.IsNotExist(err) {
fmt.Printf("%s does not exist\n", path)
}
You would find it also in loop:
If you only need the second item in the range (the value), use the blank identifier, an underscore, to discard the first:
sum := 0
for _, value := range array {
sum += value
}
The Go compiler won't allow you to create variables that you never use.
for i, value := range x {
total += value
}
The above code will return an error message "i declared and not used".
Since we don't use i inside of our loop we need to change it to this:
for _, value := range x {
total += value
}
The blank identifier may be used whenever syntax requires a variable name but program logic does not, for instance to discard an unwanted loop index when we require only the element value.
Excerpt From:
The Go Programming Language (Addison-Wesley Professional Computing Series)
Brian W. Kernighan
This material may be protected by copyright.
_ is the blank identifier. Meaning the value it should be assigned is discarded.
Here it is the value of example key that is discarded. The second line of code would discard the presence boolean and store the value in prs.
So to only check the presence in the map, you can discard the value. This can be used to use a map as a set.
The great use case for the unused variable is the situation when you only need a partial output. In the example below we only need to print the value (state population).
package main
import (
"fmt"
)
func main() {
statePopulations := map[string]int{
"California": 39250017,
"Texas": 27862596,
"Florida": 20612439,
}
for _, v := range statePopulations {
fmt.Println(v)
}
}
It is called the blank identifier and it helps in cases where you wish to discard the value that is going to be returned and not reference it
Some places where we use it:
A function returns a value and you don't intend to use it in the
future
You want to iterate and need an i value that you will not be
using
Basically, _, known as the blank identifier. In GO we can't have variables that are not being used.
As an instance when you iterating through an array if you are using value := range you don't want a i value for iterating. But if you omit the i value it will return an error. But if you declare i and didn't use it, it will also return an error.
Therefore, that is the place where we have to use _,.
Also it is used when you don't want a function's return value in the future.
An unused variable is not allowed in Golang
If you were coming from other programming languages this might feel bit difficult to get used to this. But this results in more cleaner code. So by using a _ we are saying we know there is a variable there but we don't want to use it and telling the compiler that does not complain me about it. :)
_(underscore) in Golang is known as the Blank Identifier. Identifiers are the user-defined name of the program components used for the identification purpose. Golang has a special feature to define and use the unused variable using Blank Identifier. Unused variables are those variables that are defined by the user throughout the program but he/she never makes use of these variables.
Go compiler throws an error whenever it encounters a variable declared but not used. Now we can simply use the blank identifier and not declare any variable at all.
// Golang program to show the compiler
// throws an error if a variable is
// declared but not used
package main
import "fmt"
// Main function
func main() {
// calling the function
// function returns two values which are
// assigned to mul and div identifier
mul, div := mul_div(105, 7)
// only using the mul variable
// compiler will give an error
fmt.Println("105 x 7 = ", mul)
}
// function returning two
// values of integer type
func mul_div(n1 int, n2 int) (int, int) {
// returning the values
return n1 * n2, n1 / n2
}
Output
./prog.go:15:7: div declared and not used
Let’s make use of the Blank identifier to correct the above program. In place of div identifier just use the _ (underscore). It allows the compiler to ignore declared and not used error for that particular variable.
// Golang program to the use of Blank identifier
package main
import "fmt"
// Main function
func main() {
// calling the function
// function returns two values which are
// assigned to mul and blank identifier
mul, _ := mul_div(105, 7)
// only using the mul variable
fmt.Println("105 x 7 = ", mul)
}
// function returning two
// values of integer type
func mul_div(n1 int, n2 int) (int, int) {
// returning the values
return n1 * n2, n1 / n2
}
Output
105 x 7 = 735