在 Scala 中一切都是对象 [英] Everything's an object in Scala

查看:47
本文介绍了在 Scala 中一切都是对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Scala 的新手,经常听说在 Scala 中一切都是对象.我不明白的是一切都是对象"的优势是什么?如果一切都不是对象,我不能做哪些事情?欢迎举例.谢谢

I am new to Scala and heard a lot that everything is an object in Scala. What I don't get is what's the advantage of "everything's an object"? What are things that I cannot do if everything is not an object? Examples are welcome. Thanks

推荐答案

让一切"成为对象的优势在于,抽象中断的情况要少得多.

The advantage of having "everything" be an object is that you have far fewer cases where abstraction breaks.

例如,方法不是 Java 中的对象.所以如果我有两个字符串,我可以

For example, methods are not objects in Java. So if I have two strings, I can

String s1 = "one";
String s2 = "two";
static String caps(String s) { return s.toUpperCase(); }
caps(s1);  // Works
caps(s2);  // Also works

因此,我们在制作大写字母的操作中抽象出了字符串标识.但是,如果我们想抽象出操作的身份——也就是说,我们对返回另一个字符串的字符串做某事,但我们想抽象掉细节是什么怎么办?现在我们卡住了,因为方法不是 Java 中的对象.

So we have abstracted away string identity in our operation of making something upper case. But what if we want to abstract away the identity of the operation--that is, we do something to a String that gives back another String but we want to abstract away what the details are? Now we're stuck, because methods aren't objects in Java.

在 Scala 中,方法可以转换为函数,它们是对象.例如:

In Scala, methods can be converted to functions, which are objects. For instance:

def stringop(s: String, f: String => String) = if (s.length > 0) f(s) else s
stringop(s1, _.toUpperCase)
stringop(s2, _.toLowerCase)

现在我们已经抽象出对非空字符串执行一些字符串转换的想法.

Now we have abstracted the idea of performing some string transformation on nonempty strings.

如果这是我们需要做的,我们可以列出操作等并传递它们.

And we can make lists of the operations and such and pass them around, if that's what we need to do.

还有其他不太重要的情况(对象与类、原始与非、值类等),但最重要的是消除方法和对象之间的区别,以便传递和抽象功能就像就像传递和抽象数据一样简单.

There are other less essential cases (object vs. class, primitive vs. not, value classes, etc.), but the big one is collapsing the distinction between method and object so that passing around and abstracting over functionality is just as easy as passing around and abstracting over data.

这篇关于在 Scala 中一切都是对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆