我試圖在 Scala 變數中存盤來自 2 個獨立 Java 類的非靜態或靜態方法。我該怎么做?
它類似于這個
// 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)
}
}
uj5u.com熱心網友回復:
好的,我找到了一種在使用 Scala 命令列的同時實作它的方法
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 _
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/403826.html
標籤:
上一篇:Spark:從輸出RDD中提取值
