【问题标题】:Can I reference a Method from a Scala class as a var?我可以将 Scala 类中的方法作为 var 引用吗?
【发布时间】:2022-01-28 01:18:17
【问题描述】:

我正在尝试将来自 2 个独立 Java 类的非静态或静态方法存储在 Scala var 中。我该怎么做?

和这个差不多

// 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)
   }
}

【问题讨论】:

  • Int => Int?无论如何,你不应该使用var,而是从match返回函数
  • @LuisMiguelMejíaSuárez,我正在尝试将其保存到一个 var 以便在 Main 对象的其他方法中访问。返回函数也可以,但我将如何实现呢?
  • nvm,我找到了
  • 您可以将该函数作为另一个类的参数传递,并避免使用var

标签: scala


【解决方案1】:

好的,我找到了一种在弄乱 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 _

【讨论】:

    猜你喜欢
    • 2016-07-11
    • 2023-04-10
    • 1970-01-01
    • 2012-08-22
    • 2011-06-26
    • 1970-01-01
    • 2013-10-19
    • 2015-12-29
    • 1970-01-01
    相关资源
    最近更新 更多