I'm trying to store either a non-static or static method from 2 separate Java classes in a Scala var. How should I do this?
It's similar to this
// java code below
public class Class1 {
public Static int f(int n) {
return n;
}
}
public class Class2 {
public Class2() {}
public int f(int n) {
return n 1;
}
}
// pseudocode of the scala code below
object Main {
var someFunction = _ // How do I typecast this?
def main( ... ) {
something match {
case Some(_) =>
someFunction = Class1.f // How do I set this?
case None =>
Object2 = new Class2
someFunction = Object2.f // How do I set this?
}
someFunction(1)
}
}
CodePudding user response:
Ok, I found a way to implement it while messing with Scala command line
object O1 {
// the static method
def f(n: Int): Int = {
return n
}
}
class O2(m: Int) {
// the nonstatic method
def f(n: Int): Int = {
return n m
}
}
// the _ is to explicitly show that the function type is expected
// Int => Int is the type casting for a function that takes an Int and returns an Int
var f: Int => Int = O1.f _
// Constructs an O2 and gets f
var f: Int => Int = (new O2(1)).f _
