I m trying to learn scala these days.
I get confused with _ operator.
How can I use it in the following program ?
Also how this program can be made more concise ?
I have learnt that scala promotes the use of val over var, in this case how can we use val for balance ?
private object Main {
def main(args: Array[String]): Unit = {
val acc1 = new PiggyBank(5)
acc1.printBalance
acc1 deposit 5
acc1.printBalance
acc1 withdraw 5
acc1.printBalance
}
}
private class PiggyBank(open_Bal: Int) {
var balance = open_Bal
def deposit(value: Int) = balance = balance + value
def printBalance = println(balance)
def iswithdrawable(value: Int) = balance >= value
def withdraw(value: Int) = {
if (iswithdrawable(value)) {
balance = balance - value
}
}
}
Thanks in Advance 🙂
You’re probably going to get a million answers here 🙂 But, based on the content of your question, you need to read a book. I’d recommend Programming in Scala 2nd Edition. I’ve read it twice and it’s gotten dog-eared and coffee stained in the process.
The reason I say this is because Scala presents you with a new paradigm, and you’re writing Java code in Scala. This is perfectly fine for starters but you’re not going to learn what you want to learn that way. The book is a great start that will give you the foundation to learn more.
For example, here’s what I’d change in your code:
But “why” I would want to do it that way is the real question, and it’s that question that you really need to have answered, I argue. In a nutshell, it’s immutable and a bit more functional (although, this is a toy example and there’s tons of room for improvement here), but why is it and why do we care? Books answer this stuff.
Given that, you can start to use the
_a bit if you want. For example:But if you’re like most noobs (like me a long while ago), you’re going to ask “Why on earth is that better??”. That’s not an answer you’re going to find in a quick SO post. I could go on and on and on and on but the bottom line is that there are books out there that have already done that, and have done that better than I can.