modify the function using functional programming - kotlin

Please help me, I started learning kotlin and got to functional programming. I need this set to have exactly 9 elements. Please tell me.
val uniquePatrons : Set<String> = generateSequence {
val first = patronList.randomizer()
val last = lastName.randomizer()
"$first $last"
}.take(10).toSet()

Related

How to get an Int input from user in Kotlin

I am currently creating an othello game in Kotlin. I have used Kotlin before in a robotics format, where I really didn't need to display text. Now that I am creating a user Int input to place a piece, I'm not really sure what to do. I've looked everywhere and kept on getting errors. Does anyone know how to do this? (function where I do the input is down below) the rest of the code is here : https://github.com/Spanini2/othello
fun main() {
var board = othelloBoard
var cPlayer = 'X'
setupBoard(board)
while (true) {
showBoard(board)
println("It is player $cPlayer 's turn")
println("Enter coords of move:")
var xInput = readLine()!!.toInt()
var yInput = readLine()!!.toInt()
placePiece(board, xInput, yInput, cPlayer)
}
}

Kotlin Map with If statement

Trying to write some Functional code and use map - maybe filter too? - to replace something like:
for (something in somethingList) {
if (something.value == someOtherThing.value)
result = true
}
With something more functional like found here: https://grokonez.com/kotlin/kotlin-filter-map-examples
But I don't want to return a new map I want to set result to the condition of something.value == someOtherThing.value being true or not.
But I'm getting lost in my neophyte world of Functional Kotlin.
Can anyone nudge me in the right direction?
Thanks
You can use any for this purpose.
val result = somethingList.any { it.value == someOtherThing.value }

Bind listview to config sourced property

I'm attempting to follow the guide to try to persist multiple choices from two lists to config. (https://edvin.gitbooks.io/tornadofx-guide/part2/Config%20Settings%20and%20State.html). The guide only discusses SimpleStringProperty in this context. I can see that I should be using SimpleListProperty, but I don't see the right way to associate it with config.
My rough attempt so far:
data class Devices(val receivers: List<String>, val transmitters: List<String>)
// XXX I'd like to just persist Devices, but I'm exposing separate properties for the constituents of Devices
class DevicesModel: ItemViewModel<Devices>() {
// XXX type ends up as Property<ObservableList<JsonValue>>, which seems wrong
val receivers = bind { SimpleListProperty(this, "receivers", config.jsonArray("receivers")!!.toObservable()) }
val transmitters = bind { SimpleListProperty(this, "transmitters", config.jsonArray("transmitters")!!.toObservable()) }
}
class FooView: View() {
val devicesModel = DevicesModel()
// XXX this wants a ReadOnlyListProperty, rather than what it's getting
fun receivers() = listview<String>(devicesModel.receivers) {
selectionModel.selectionMode = SelectionMode.MULTIPLE
}
fun transmitters() = listview<String>(devicesModel.transmitters) {
selectionModel.selectionMode = SelectionMode.MULTIPLE
}
}
Obviously I haven't tackled commit etc, which I will. My question is about the binding/association specifically -- where have I gone wrong? My lack of JavaFX / UI programming background is probably hurting me here.
I have three questions marked with XXX in code, specifically:
I have a mismatch between the properties I'm exposing and the data class. I suppose this could be dealt with in the commit, but that seems messy.
The typing on the properties themselves (particularly JsonValue being exposed) seems wrong, but I don't see a way to expose what I'm looking for.
Why does listview() want a ReadOnlyListProperty? How do I make this accept an Observable?
I will post a PR to the guide with an example, and some clarifying explanation, once I get this working.

Kotlin supplyAsync with executor

I want to create a CompletableFuture with a return value that runs on a specific executor in Kotlin.
The following code works just fine.
return CompletableFuture.supplyAsync {
val commandHandler = registry.get<TCommand, TResponse>(command::class.java)
commandHandler.handle(command)
}
However when I attempt to pass the executor it won't compile.
return CompletableFuture.supplyAsync({
val commandHandler = registry.get<TCommand, TResponse>(command::class.java)
commandHandler.handle(command)
}, exec)
I tried to get clever and wrote the Java version and had Intellij covert it to Kotlin, but that one had the same error as well. What am I doing wrong here?
EDIT:
I can make it work by doing the following but it seems unnecessary. Can someone explain why this works but other methods do not. Are there other ways to write this code?
return CompletableFuture.supplyAsync(Supplier {
commandHandler.handle(command)
}, exec)
I do not exactly know, why it is not working. But the following does work:
return CompletableFuture.supplyAsync({
val commandHandler = registry.get<TCommand, TResponse>(command::class.java)
commandHandler.handle(command)
}, exec::execute)
As you can see, I changed the second parameter to a method reference.
Now the signature of the method is:
supplyAsync(supplier: () -> U, executor: (Runnable)-> Unit)
If you pass the Executor directly, Kotlin chooses the signature:
supplyAsync(supplier: Supplier<U>, executor: Executor)
It looks like you can not mix interface and lambda style.

Scope of variable defined in for loop header

I noticed that the following Kotlin code compiles and executes successfully:
for (i in 1..2) {
val i = "a"
print(i)
}
This prints aa. However, I failed to find rationale behind the decision to allow this kind of variable shadowing. I would say that this is not a good practice, and is prohibited even in Java.
I think that Kotlin designers did a great work of improving Java syntax and accommodating it to the everyday practical use, so I must be missing something here?
Kotlin does not restrict variable shadowing in any way. The rationale is simple: "consistency."
Since you could shadow variables in most other places why would you exclude only some loop variables from the allowed options? Why would they be so special? It is an arbitrary difference.
Any scope can shadow a variable used in another scope. It is NOT good practice and does produce a compiler warning -- but it is allowed.
If you want to engage in a dialog with the contributors of the project, try the discussion forum or slack channel, both are linked from the Kotlin Community page. Otherwise if you feel it is a bug please add an Issue report to Kotlin YouTrack and the answer you receive there will be definitive as well.
In the meantime, you are free to write nonsensical code such as:
val i = 1
class Foo() {
val i = "monkey"
init { println(i) }
#Test fun boo() {
println(i)
val i = i.length
println(i)
if (i == 6) {
val i = Date(System.currentTimeMillis() + i) // Shadow warning
println(i)
}
for (i in 0..i) { // Shadow warning
val i = "chimp $i" // Shadow warning
println(i)
}
InnerFoo()
}
class InnerFoo() {
val i: Long = 100L
init { println(i) }
}
}
Which in Kotlin 1.0.3 produces 3 warnings.
Warning:(15, 21) Kotlin: Name shadowed: i
Warning:(18, 18) Kotlin: Name shadowed: i
Warning:(19, 21) Kotlin: Name shadowed: i
And outputs:
monkeymonkey6Sun Jul 17 11:31:23 UYT 2016chimp 0chimp 1chimp 2chimp 3chimp 4chimp 5chimp 6100