scala protected modifier convert to java class is public - scala

In a scala class, I have defined a protected field and a protected method:
TestProtected.scala:
class TestProtected {
protected var f = 0
protected def m = 1
}
In my opinion, it will convert the protected f and m to a java protected filed and method. But when i use jd-gui to decompiler the TestProtected.class to java file, the result was beyond my expectation:
#ScalaSignature(bytes="...")
public class TestProtected
{
private int f= 0;
public int f() { return this.f; }
public void f$eq(int x$1) { this.f = x$1; }
public int m() {
return 1;
}
}
The f and m in java file is public?
Why?
Thanks!

Firstly, Scala protected is different from Java protected:
Java's protected is visible to same package and subclass, Scala protect is only visible to subclass, so Scala's protected is more restrictive than Java's.
So this is caused by JVM Level access modifier is not same as Scala access modifier, we know Scala runs on JVM, for running on JVM, it needs to generate the compatible byte code in JVM.
There are some other example like:
private
private[this]
private[package]
There are some reference about Scala Access:
Protected and private in Scala become public in Java
Scala Access
Protected Members

I'm not sure, but this may be because companion object of a class should also be able to access protected members of a class in scala. And because companion object is actually a different class from its companioin class, scala has to compile protected members to public in a bytecode.

Related

Can a Scala compiler plugin transform the autogenerated accessor methods of scala case classes?

After the parser phase of the Scalac process, the following case class
case class ExampleCaseClass(var s:String, var i:Int) extends ContextuallyMutable
takes the intermediate form:
Clazz(case class ExampleCaseClass extends ContextuallyMutable with scala.Product with scala.Serializable {
<caseaccessor> <paramaccessor> var s: String = _;
<caseaccessor> <paramaccessor> var i: Int = _;
def <init>(s: String, i: Int) = {
super.<init>();
()
}
})
However, a run time reflection call:
ExampleCaseClass("Can a Scala compiler plugin transform the autogenerated accessor methods of scala case classes?", 42).getClass.getMethods.foreach(println(_))
reveals many more public methods:
public boolean ExampleCaseClass.equals(java.lang.Object)
public java.lang.String ExampleCaseClass.toString()
public int ExampleCaseClass.hashCode()
public static ExampleCaseClass ExampleCaseClass.apply(java.lang.String,int)
public int ExampleCaseClass.i()
public java.lang.String ExampleCaseClass.s()
public ExampleCaseClass ExampleCaseClass.copy(java.lang.String,int)
public void ExampleCaseClass.i_$eq(int)
public scala.collection.Iterator ExampleCaseClass.productElementNames()
public java.lang.String ExampleCaseClass.productElementName(int)
public void ExampleCaseClass.s_$eq(java.lang.String)
public int ExampleCaseClass.copy$default$2()
public boolean ExampleCaseClass.canEqual(java.lang.Object)
public java.lang.String ExampleCaseClass.productPrefix()
public int ExampleCaseClass.productArity()
public java.lang.Object ExampleCaseClass.productElement(int)
public scala.collection.Iterator ExampleCaseClass.productIterator()
public java.lang.String ExampleCaseClass.copy$default$1()
public static scala.Function1 ExampleCaseClass.tupled()
public static scala.Option ExampleCaseClass.unapply(ExampleCaseClass)
public static scala.Function1 ExampleCaseClass.curried()
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
Clearly some subsequent compiler phase creates the property accessor methods:
public int ExampleCaseClass.i()
public java.lang.String ExampleCaseClass.s()
public void ExampleCaseClass.i_$eq(int)
public void ExampleCaseClass.s_$eq(java.lang.String)
Which compilation phase generates these accessor methods and what manner of compiler plugin (or other means) might prevent or transform them?
The enquirer has already run numerous experiments removing or reshaping the:
<caseaccessor> <paramaccessor> var s: String = _;
<caseaccessor> <paramaccessor> var i: Int = _;
portions of the case class, and also with injecting the desired accessor methods in advance but no combination has met the desired outcome. They either fail to compile because of naming conflicts that arise in subsequent compilation phases, or they alter the parameter names in constructor, apply, and accessor methods.
Can a scala compiler plugin transform synthetic accessors at all? Does the Java Compiler introduce these methods? If so, should the enquirer look to Javac plugins and what analogues might serve the Scala.js and Scala native compilation targets?
Thank you for any consideration.
case class expansion happens in more than one place, see another question.
Instead of writing a new plugin just to disallow using var it would be much better to add a new rule to Wartremover or ScalaFix. As a matter of the fact, these rules already exist:
disallow var with Wartremover - combine it with fatal warnings to fail compilation on var
disallow var with ScalaFix
If you want to add more elaborate rule... it would still be easier just to write your own Wartremover/ScalaFix rule (the latter might be preferred as it is already supported in Scala 3).
And if you really need a custom compiler plugin to mess with code generated by compiler... take a look at better-toString plugin. It adds its own phase after "parser" phase. But I wouldn't hope for removing the autogenerated implementations. At best you can override them manually where specs allows you to.
The enquirer found a Scala 3 solution with persistence and help from examples:
better-tostring a plugin that demonstrates conditional method insertion by Polyvariant.
Compiler Plugin Development in Scala 3 Example and Tutorial by Scala Center dev: Fengyun Liu. The video provided insights into compiler phases and the example shed light on method body generation syntax. In particular, available documentation doesn't readily clarify how to call println from a method body generated as a Tree by a compiler plugin, but Liu's example plugin demonstrated requireModule and requiredMethod.
Scala 3 Compiler Plugin Documentation offers a very nice template for how to start writing a plugin. The final solution looked very similar.
As of 26 Nov 2021, no solution exists for Scala 2.13, but maybe that just means it is time to upgrade.
final class BlockMutatorPlugin extends StandardPlugin {
override val name: String = "BlockMutatorPlugin"
override val description: String = "Scala Compiler Plugin for blocking ContextuallyMutable setter methods."
override def init(options: List[String]): List[PluginPhase] = List(new BlockContextuallyMutableSetters)
}
class BlockContextuallyMutableSetters extends PluginPhase {
val phaseName = "blockGetter"
/* Running this plugin after phases before ElimErasedValueType
resulted in the replacement of the generated setter methods by the synthetic
default versions. By the time that this ElimErasedValueType phase ends, the
defaults already existed, so this plugin could augment them safely. */
override val runsAfter = Set(ElimErasedValueType.name)
private var printBlocked: Tree = _
override def prepareForTemplate(tree: tpd.Template)(using ctx: Context): Context = {
val cnsl = requiredModule("scala.Predef")
val prntln: PreName = "println".toTermName
val say = cnsl.requiredMethod(prntln, List[Types.Type](ctx.definitions.ObjectType))
printBlocked = ref(say).appliedTo(Literal(Constant("Blocked!")))
ctx
}
override def transformTemplate(tree: Template)(using ctx: Context): Tree = {
if (tree.parents.filter(_.symbol.name.toString.equals("ContextuallyMutable")).nonEmpty) {
cpy.Template(tree)(
body = tree.body.collect {
case dd: DefDef if dd.name.isSetterName => DefDef(
dd.symbol.asInstanceOf[Symbols.TermSymbol],
printBlocked
)
case x => x
}
).asInstanceOf[Tree]
} else tree
}
}
The most important part of this effort involved discovering which compiler phase this plugin should follow. Similar efforts in Scala 2.13.6 have failed so far; the only remaining impediment to the Scala 2 solution sought by this original Stack Overflow question. As such, the enquirer will not mark his own answer as the accepted solution unless future edits avail Scala 2. Until that time, your response may claim that designation.
For any inclined to try compile this example, the code above requires the following import statements:
import dotty.tools.dotc.ast.tpd
import tpd.*
import dotty.tools.dotc.core.*
import Names.PreName
import Symbols.{ClassSymbol, requiredMethod, requiredModule}
import Decorators.*
import NameOps.*
import Contexts.Context
import Constants.Constant
import dotty.tools.dotc.plugins.*
import dotty.tools.dotc.transform.ElimErasedValueType

Why we cannot mark the visibility of a class as "protected" in kotlin?

I am new to kotlin I have been learning about inheritance in kotlin recently, and then I realised that we cannot mark the visibility of a class as "protected". Correct me if i am wrong, or is there any other way to make a class protected ?
You can mark protected only parts of classes, so that they become accessible only from the derived classes. You can mark protected a member property, a member function or a nested class:
open class X {
protected val v: SomeType = someValue
protected fun f() { }
protected class Y { ... }
}
But you cannot mark protected anything that does not belong to a class (e.g. a top-level class or function), because the modifier would make no sense: a top-level entity is not subject to inheritance, thus there can be no derived class that would access it.

How to implement a Java abstract interface in Scala

How do you implement a Java abstract interface in scala?
Abstract interface :
public abstract interface KeyIndex<K>
extends Serializable
{
public abstract long toIndex(K paramK);
public abstract Seq<Tuple2<Object, Object>> indexRanges(Tuple2<K, K> paramTuple2);
}
It seems, that your KeyIndex class is written in Java. In Scala every field not labeled private or protected is public. There is no public keyword in Scala.
But implementing a Java class in Scala is possible:
class KeyIndexImpl extends KeyIndex[geotrellis.spark.SpatialKey]{
override def toIndex(paramK: geotrellis.spark.SpatialKey): Long =
1l
override def indexRanges(paramTuple2: (geotrellis.spark.SpatialKey, geotrellis.spark.SpatialKey)): Seq[(AnyRef, AnyRef)] =
Seq((paramTuple2, paramTuple2))
}

What's the implication of protected keywords in class definition in Scala?

I'm learning Scala by working the exercises from the book "Scala for the Impatient". One exercise asks that:
The file Stack.scala contains the definition class Stack[+A]
protected (protected val elems: List[A])
Explain the meaning of the protected keywords.
Can someone help me understand this? protected obviously makes sense for member variables but what implication does it have in a class definition?
In Scala, writing
class Stack[+A](elems: List[A])
also implements a default constructor. If you know Java, then in Java this would be something like
class Stack<A> {
private List<A> elems;
public Stack<A>(List<A> elems){this.elems = elems;}
}
Now, you have two protected keywords in your example:
protected val elems: List[A]
protected (/*...*/)
The first makes the variable elems protected, meaning it can only be accessed (and shadowed) by subclasses of Stack[+A].
The second makes the constructor protected, meaning that a new Stack instance can only be created by subclasses of Stack[+A].
Again, the equivalent Java code would be something like
class Stack<A> {
protected List<A> elems;
protected Stack<A>(List<A> elems){this.elems = elems;}
}

Object-private variables implementation

I'm trying to understand implementation of object-private variables in Scala. Scala compiles this class
class Counter{
private[this] var age = 0
}
into the following java byte code:
public class Counter implements scala.ScalaObject {
private int age;
public Counter();
}
But still, because JVM doesn't support object-private fields, we have good-old private field, which can be accessed from other instances of the class. So for me the difference between previous class and the following in terms of hiding private field is not clear.
class Counter2{
private var age = 0
}
public class Counter2 implements scala.ScalaObject {
private int age;
private int age();
private void age_$eq(int);
public Counter2();
}
The JVM is irrelevant. The semantics of Scala are implemented by the Scala compiler, not the JVM. After all, the JVM isn't even the only platform Scala runs on, there are production-ready implementations of Scala on the CLI, and experimental ones on ECMAScript as well as a native one.