【问题标题】:Importing Functions from Other Classes in Scala从 Scala 中的其他类导入函数
【发布时间】:2014-09-07 04:20:34
【问题描述】:

比如说我有

class foo{
  def bar = 7
}

class qaz{
  //Here I want to have something like: val foobar = bar
  //What I don't want to have is val foobar = (new foo).bar   
}

我怎样才能做到这一点?

【问题讨论】:

    标签: function class scala import


    【解决方案1】:

    您可以使用foo 的伴随对象来定义bar

    然后你就可以简单的导入到qaz:

    // in foo.scala
    object foo {
      def bar = 7
    }
    class foo {
      // whatever for foo class
    }
    
    // in qaz.scala
    import mypackage.foo.bar
    class qaz {
      val foobar = bar     // it works!
    }
    

    【讨论】:

    • 为此,foo 需要成为 foo.scala 的伴生对象?我也可以有一个同伴课程吗?
    【解决方案2】:

    有两种方法可以实现:

    1. 使用伴随对象

    2. Case Class

    第二种方法,即需要包含伴随对象的方法,正如 Jean 已经实现的那样:

    class foo {
    // whatever for foo class
    }
    
    //Companion Object
    object foo {
        def bar = 7
    }
    
    class qaz {
      val foobar = bar 
    }
    

    通过创建一个case类而不是一个普通的类,为你创建了很多样板代码,其中一个是apply方法的生成,所以你不需要使用new关键字来创建一个新的实例类的。

    case class foo{
      def bar = 7
    }
    
    class qaz{
       val foobar = bar  
    }
    

    这两种方法都是一种语法糖,但在后面做同样的事情,即在伴生对象中使用 apply 函数。 请尝试this 了解更多信息。

    【讨论】:

    • 具体指的是哪一部分?
    • case class foo { ... }(在第二种情况下,除非使用非常旧的 Scala 版本)和val foobar = bar(在这两种情况下)。
    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多