i am wondering is there some syntax in Kotlin for declaring a variable which will be equal to a function which takes several parameters 1 of which is said variable?
class Player(var deck: MutableList<String> = Deck().deck) {
var playerHand = Deck().deal(deck, playerHand, 6)
}
class Deck {
var deck = mutableListOf<String>()
fun deal( from: MutableList<String>, to: MutableList<String>, num: Int ){
var temp = from.slice(0 .. num).toMutableList()
to.addAll(temp)
from.removeAll(temp)
}
}
So i basically want to transfer N amount of cards from a deck inside a Deck class to a variable playerHand in Player class. I know there are numerous other ways of doing it, i just wanted to know is there a way to create a var and assign a value to it using a function that takes that var as a parameter..
CodePudding user response:
I stared at your code for a while and finally realized what you're asking, I think: You want playerHand
to be a MutableList whose initial values come from calling Deck().deal()
. Like @broot says in the comment, the standard way to do this is to use also
. I'm also assuming it's some kind of typo that you are instantiating a new Deck instance to deal from, when you already have a deck property in your class. However, that property should probably be a Deck instance directly so you still have access to the Deck functionality that goes with it.
You might consider making your Deck class implement MutableList using a delegate to simplify how it is referenced and used. Now you can directly use existing MutableList functions like shuffle()
directly on your Deck instance. And I would use LinkedList specifically as the delegate because it is more efficient than the default returned by mutableListOf
at removing values from the top.
I would also make the deal
function simply a dealTo
function because it should be assumed a Deck is only going to deal from itself.
Putting that all together:
class Player(var deck: Deck = Deck()) {
val playerHand = mutableListOf<String>().also {
deck.dealTo(it, 6)
}
}
class Deck: MutableList<String> by LinkedList<String>() {
fun dealTo(to: MutableList<String>, num: Int) {
repeat(num) {
to = removeFirst()
}
}
}