简体   繁体   English

Scala中的python @classmethod或@staticmethod等效于什么?

[英]What's the equivalent of a python @classmethod or @staticmethod in Scala?

当我不想使用隐式但希望有一个将(例如) Int转换为MyClass的函数时,这很有用。

In Scala, an object is used to define static methods. 在Scala中,一个object用于定义静态方法。 What you are describing sounds like you want this: 您正在描述的声音听起来像这样:

class MyClass(n: Int)

object MyClass {
  def apply(n: Int) = new MyClass(n)
}

So that you can do either of these: 这样您就可以执行以下任一操作:

scala> val a = MyClass.apply(3)
a: MyClass = MyClass@70d1c9b5

scala> val b = MyClass(3)       // works allowed because method is called "apply"
b: MyClass = MyClass@1b4b2db7

I would call this a "factory method". 我将其称为“工厂方法”。

You can put a method into the companion object to call it in a static way from Scala (ie without an object instance): 您可以将方法放入伴随对象,以从Scala以静态方式调用它(即,没有对象实例):

// Scala
class A
object A {
  def staticMethod = println("Foo!")
}
A.staticMethod // prints "Foo!"

note that the Scala compiler actually creates a new synthetic class called A$ for the singleton object A , so the line A.staticMethod calls the method on a single instance of A$ which exists at runtime. 请注意,Scala编译器实际上为单例object A创建了一个称为A$的新合成类,因此A.staticMethod运行时存在的A$单个实例上调用该方法。

Noteworthy: The Scala compiler also creates a static method staticMethod in A on the bytecode level which forwards the call to A$.staticMethod - in case you're mixing Java and Scala code in your project, this means that you will also be able to call this static method from Java like this: 值得注意的是:Scala编译器还在字节码级别的A创建了一个静态方法staticMethodA方法将调用转发给A$.staticMethod如果您在项目中混合了Java和Scala代码,这意味着您还可以从Java调用此静态方法,如下所示:

// Java
A.staticMethod(); // works

However, if you declare the method with the same name in the companion class A , while everything still works in the same way in Scala, the static forwarder method in A will not be generated, and you will not be able to call staticMethod from Java: 但是,如果在同伴类A中用相同的名称声明该方法,而在Scala中一切仍以相同的方式工作,则不会生成A的静态转发器方法,并且您将无法从Java调用staticMethod

// Scala
class A {
  def staticMethod = println("I'm doing something else.")
}
object A { // no companion class
  def staticMethod = println("Foo!")
}
A.staticMethod // prints "Foo!"

// Java
A.staticMethod(); // won't work

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM