I want to write equivalent of this Java code in Scala:
final Object foo;
if (/*...*/) {
foo = /* something */;
} else {
foo = /* something else */;
use(foo);
}
useDifferently(foo);
and I am looking for equivalent in Scala. I can't let the variable uninitialized until first use (neither with val or var), so I am forced to write something like
val foo = if (/*...*/) {
/* something */
} else {
val tmp = /* something else */
use(tmp)
tmp
}
useDifferently(foo)
I find the need for temporary variable rather inelegant. Please show me the elegant way.
There's no way to write Scala code directly analogous to your Java code, but you could make this more elegant by restructuring it to achieve greater separation of concerns. At the moment, the conditional does two things: assign a value to foo and, maybe, perform a side effect. Separating these two concerns will result in code like this:
val conditionIsSatisfied = /*...*/
val foo = if (conditionIsSatisfied) {
/* something */
} else {
/* something else */
}
if (conditionIsSatisfied) {
use(foo)
}
useDifferently(foo)
val foo = if (/*...*/) {
/* something */
} else {
/* something else */ match { case v => use(v); v}
}
useDifferently(foo)
You are actually trying to fit not java code in scala, but imperative way of development into functional. You need to write it like this:
val foo = if (/*...*/) {
/* something */
} else {
use(/* something else */)
}
useDifferently(foo)
And make "use()" return updated foo object.
Related
I am implementing a ContractNetInitiator from Jade in scala and I need to override this method:
protected void handleAllResponses(java.util.Vector responses,java.util.Vector acceptances)
And implemented it like this:
override def handleAllResponses(responses: Vector[_], acceptances: Vector[_]): Unit = {
var acceptProposal: ACLMessage = null
var bestProposal = Integer.MAX_VALUE
var bestProposer = ""
// Find best proposal and reject all proposal
val e = responses.elements()
while (e.hasMoreElements) {
val response: ACLMessage = e.nextElement().asInstanceOf[ACLMessage]
if (response.getPerformative == ACLMessage.PROPOSE) {
val reply = response.createReply()
reply.setPerformative(ACLMessage.REJECT_PROPOSAL)
acceptances.addElement(reply) // Can't add the reply : "Type mismatch, expected: _$1, actual: ACLMessage"
if (response.getUserDefinedParameter("Value").toInt < bestProposal) {
bestProposal = response.getUserDefinedParameter("Value").toInt
bestProposer = response.getSender.getLocalName
acceptProposal = reply
}
}
}
// Accept proposal
if (acceptProposal != null) {
acceptProposal.setPerformative(ACLMessage.ACCEPT_PROPOSAL)
}
}
But when I try to add a reply to acceptances I get a Type mismatch.
I tried to change "acceptances: Vector[_]" with "acceptances: Vector[ACLMessage]" and "acceptances: Vector[Any]", but it doesn't work since it doesn't correspond with the super class.
Is there a way to add elements to acceptances ?
You'll need to cast it:
acceptances.asInstanceOf[Vector[ACLMessage]].addElement(reply)
Normally it's something to avoid, but in this case it's entirely the library's fault for using raw types and only documenting effective type parameters.
Does Rust have a feature whereby I can create define potentially non-existent methods on traits?
I realize that Option can be used to handle potentially non-existent properties but I don't know how the same can be achieved with methods.
In TypeScript, the question mark denotes that the methods may potentially be non-existent. Here is an excerpt from RxJs:
export interface NextObserver<T> {
next?: (value: T) => void;
// ...
}
If this feature does not exist in Rust, how should one think about dealing with objects whereby the programmer doesn't know whether a method will be present or not? Panic?
You can try using empty default implementations of methods for this:
trait T {
fn required_method(&self);
// This default implementation does nothing
fn optional_method(&self) {}
}
struct A;
impl T for A {
fn required_method(&self) {
println!("A::required_method");
}
}
struct B;
impl T for B {
fn required_method(&self) {
println!("B::required_method");
}
// overriding T::optional_method with something useful for B
fn optional_method(&self) {
println!("B::optional_method");
}
}
fn main() {
let a = A;
a.required_method();
a.optional_method(); // does nothing
let b = B;
b.required_method();
b.optional_method();
}
Playground
I have written 2 codes .The functionality of both the code is same.Both the codes take user data then store it in map and on providing keys we get correspoding user data. I have written an extra logic in code2, whic I have mentioned below.
Code1:
class user(var name:String,var id:Int, var gender:Option[String])
{
override def toString="("+ name+","+id+","+gender+")"
}
object a
{
def main(args:Array[String]):Unit={
var a=new user("kl",90,Some("Male"))
println(a.name,a.id,a.gender)//ACESS VALUES
//DEFINING MAP
var mm=Map(1-> new user("jh",189,Some("Male")),2->new user("gh",12,None),3
->new user("io",100,Some("Female")))
// defining method giving o/p value of specific key of mm
def getkey(i:Int)=
{ mm.get(i)
}
var u1=getkey(readLine("ENTER THE KEY").toInt) // some[user]
println(u1.getClass.getName)
if(u1.isDefined)
{
println(u1.get+","+u1.get.name+","+u1.get.id+","+u1.get.gender)
}
}
}
Code1 1 works properly and O/P is right. I have added extra logic in Code2. The extra logic is getKey method. I have written a code for checking whether the input key is present in map. There I am getting an error:
**value get is not a member of java.io.Serializable**_
Code2:
class user(var name:String,var id:Int, var gender:Option[String])
{
override def toString="("+ name+","+id+","+gender+")"
}
object a
{
def main(args:Array[String]):Unit={
var a=new user("kl",90,Some("Male"))
println(a.name,a.id,a.gender)//ACESS VALUES
//DEFINING MAP
var mm=Map(1-> new user("jh",189,Some("Male")),2->new user("gh",12,None),3-> new user("io",100,Some("Female")))
// defining method giving o/p value of specific key of mm
def getkey(i:Int)=
{
//EXTRA LOGIC
var a=(mm.keys).toList
if(a.contains(i)){mm.get(i)}
else {"NO SUCH ELEMENT EXCEPTION , KEY DOESNT MATCH"}
}
print("ENTER THE KEY \n")
var u1=getkey(1) // some[user]
println(u1.get)
}
}
ERROR -
enter code here
eg1.Option.scala:27: error: value get is not a member of
java.io.Serializable
println(u1.get)
^
one error found
Why does the seriliazable errors occurs in Code2 and not in Code1? Is the error due extra logic in Code2? How to fix an error?
Thank you!
It happens because your getKey function return type is io.Serializable.
Reason for this is that every branch of your if expression is returning a different type:
def getkey(i:Int) = { // io.Serializable
//EXTRA LOGIC
var a=(mm.keys).toList
if(a.contains(i)) { mm.get(i) } // option here
else { "NO SUCH ELEMENT EXCEPTION , KEY DOESNT MATCH" } // string here
}
Consider rewriting your function, so its return type is Option[User], one way of doing so is:
def getkey(i:Int): Option[user] = {
//EXTRA LOGIC
var a=(mm.keys).toList
if(a.contains(i)) { mm.get(i) }
else { None }
}
However, there is no need for checking keys, you can simplify this function to:
def getkey(i:Int): Option[user] = {
//EXTRA LOGIC
m.get(i)
}
Hint: write expected return type for functions to see what's going wrong in such cases.
I have some expensive promises that get called in different spots. Ideally, I'd like to just chain off an existing in-flight promise (with an optional force), so I find myself doing something like this:
class Expensive {
var fooPromise : Promise<Foo>?
var barPromise : Promise<Bar>?
func doExpensiveFoo(force: bool = false) -> Promise<Foo> {
if let existing = fooPromise where existing.pending || (existing.fufilled && !force) {
// Return the existing promise
return existing
}
// Start a new Foo
return firstly {
// ...
}
}
func doExpensiveBar(force: bool = false) -> Promise<Bar> {
if let existing = barPromise where existing.pending || (existing.fufilled && !force) {
// Return the existing promise
return existing
}
// Start a new Bar
return firstly {
// ...
}
}
}
But that feels like a fair amount of boiler-plate (a local variable for each promise, and the existing chunk at the start of each function), so I'm wondering if anyone has seen a good pattern for abstracting away the variables and wrapper?
To borrow a term from Python, I'm looking for a decorator that would hide all that. Something like:
class Expensive {
private func startFoo() -> Promise<Foo> {
return firstly {
//..
}
}
public doExpensiveFoo = wrapExpensive(startFoo)
}
Any suggestions, or should I look at rolling my own?
I'm no expert, but this pattern worked for me:
private var fooPromise : Promise<Foo>?
func doExpensiveFoo() -> Promise<Foo> {
if let fooPromise = self.fooPromise, fooPromise.isPending {
// return the pending promise
return fooPromise
}
// reassign a newly created promise
fooPromise = firstly {
// do your thing
...
}
return fooPromise!
}
What I like about this pattern is that the method handles pending state internally, and that the promise automatically re-executes if called after it is finished. This allows callers to be ignorant of the internal mechanism or the state of the promise. Obviously, if you need to caller to be part of the decision, then keep the "force" flag approach.
I do not see any common base of Foo and Bar in your example. But even if they would have one Swift still does not support covariance on generic type parameters. At first you would need to create a common protocol for both types. Maybe this helps you to get on track:
Storing generic objects in Swift Array
I need to set a variable depending on a condition. But since variables are immutable, I find myself in a sticky situation having to repeat code. What I'd like to do is:
def doSomething(x:Int):Int = {
if(x==1){
val player="Andy"
} else {
val player="Rob"
}
getSomeValue(player) // Another function
}
But the variable "player" is no longer in scope. Only way I see is to call the function "getSomeValue" in both the condition blocks, but that's not something I'd like to do. How do I get around this using immutable variables?
def doSomething(x:Int):Int = {
val player = if(x==1){
"Andy"
} else {
"Rob"
}
getSomeValue(player)
}