混淆scala私有字段变量 [英] Confuse about scala private field variable

查看:44
本文介绍了混淆scala私有字段变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在进行 Scala 学习的第三天.使用书开始Scala".

I am on my third day of scala study. Using book "begin scala".

作者用一个例子来说明变量define with val var和不带var val的区别:

Te author uses an example to show the diff between variable define with val var And without var val:

class Book(private val title: String) {
   def printTitle(b: Book) {
       println(b.title)
   }
}

在控制台中:

scala> val book = new Book("Beginning Scala")
book: Book = Book@ea05be
scala> book.printTitle(new Book("Beginning Erlang"))
Beginning Erlang

这里让我困惑的不是有/没有 val var,而是私有修饰符:

Here what confused me is not with/without val var, but the private modifier:

我不确定我是否理解私有权利,但是如果 Scala 想要 title 作为私有字段,那么 为什么它允许其他人从外部访问它,我认为prinTitle 应该无法访问 new Book("Beginning Erlang") 的 title 字段

I am not sure if I understand private right, but if scala want title as private field, then why it allows others to access it from outside, I thought the prinTitle should not be able to access new Book("Beginning Erlang")'s title field

推荐答案

title 的值是 private 的类,而不是实例,因为方法 printTitle 是类的成员,它可以访问其他实例的私有值.

The value title is private to the class, not to the instance, Since the method printTitle is a member of the class, it can access private values of other instances.

如果您希望 title 对实例是私有的,您可以改用 private[this] 修饰符.

If you wanted title to be private to the instance, you would use the private[this] modifier instead.

此外,private[package] 修饰符,其中 package 是定义所在的包的名称,可以与包共享私有成员.例如

Further, the private[package] modifier, where package is the name of the package the definition occurs in, can share the private member with the package. For example

package com.sample.foo

class Book(private[foo] title: String)

将可供 com.sample.foo

这篇关于混淆scala私有字段变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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