diff --git a/library/src/scala/App.scala b/library/src/scala/App.scala index 75b0a0c78adf..f1d098b2b942 100644 --- a/library/src/scala/App.scala +++ b/library/src/scala/App.scala @@ -62,7 +62,7 @@ import scala.collection.mutable.ListBuffer * } * }}} */ -@nowarn("""cat=deprecation&origin=scala\.DelayedInit""") +@nowarn("cat=deprecation") trait App extends DelayedInit { /** The time when the execution of this program started, in milliseconds since 1 @@ -73,9 +73,9 @@ trait App extends DelayedInit { */ protected final def args: Array[String] = _args - private[this] var _args: Array[String] = _ + private var _args: Array[String] = compiletime.uninitialized - private[this] val initCode = new ListBuffer[() => Unit] + private val initCode = new ListBuffer[() => Unit] /** The init hook. This saves all initialization code for execution within `main`. * This method is normally never called directly from user code. diff --git a/library/src/scala/Array.scala b/library/src/scala/Array.scala index bb23b79eb1a4..e40d82b0ed17 100644 --- a/library/src/scala/Array.scala +++ b/library/src/scala/Array.scala @@ -152,7 +152,7 @@ object Array { * * @see `java.util.Arrays#copyOf` */ - def copyAs[A](original: Array[_], newLength: Int)(implicit ct: ClassTag[A]): Array[A] = { + def copyAs[A](original: Array[?], newLength: Int)(implicit ct: ClassTag[A]): Array[A] = { val runtimeClass = ct.runtimeClass if (runtimeClass == Void.TYPE) newUnitArray(newLength).asInstanceOf[Array[A]] else { diff --git a/library/src/scala/Console.scala b/library/src/scala/Console.scala index 0c89da155b65..3f355c350521 100644 --- a/library/src/scala/Console.scala +++ b/library/src/scala/Console.scala @@ -126,9 +126,9 @@ import scala.util.DynamicVariable * */ object Console extends AnsiColor { - private[this] val outVar = new DynamicVariable[PrintStream](java.lang.System.out) - private[this] val errVar = new DynamicVariable[PrintStream](java.lang.System.err) - private[this] val inVar = new DynamicVariable[BufferedReader]( + private val outVar = new DynamicVariable[PrintStream](java.lang.System.out) + private val errVar = new DynamicVariable[PrintStream](java.lang.System.err) + private val inVar = new DynamicVariable[BufferedReader]( new BufferedReader(new InputStreamReader(java.lang.System.in))) protected def setOutDirect(out: PrintStream): Unit = outVar.value = out @@ -279,5 +279,5 @@ object Console extends AnsiColor { * @throws java.lang.IllegalArgumentException if there was a problem with the format string or arguments * @group console-output */ - def printf(text: String, args: Any*): Unit = { out.print(text.format(args: _*)) } + def printf(text: String, args: Any*): Unit = { out.print(text.format(args*)) } } diff --git a/library/src/scala/Enumeration.scala b/library/src/scala/Enumeration.scala index 2e5347472826..c5b7905573ad 100644 --- a/library/src/scala/Enumeration.scala +++ b/library/src/scala/Enumeration.scala @@ -99,8 +99,12 @@ abstract class Enumeration (initial: Int) extends Serializable { /** The name of this enumeration. */ override def toString: String = - ((getClass.getName stripSuffix MODULE_SUFFIX_STRING split '.').last split - Regex.quote(NAME_JOIN_STRING)).last + getClass.getName + .stripSuffix(MODULE_SUFFIX_STRING) + .split('.') + .last + .split(Regex.quote(NAME_JOIN_STRING)) + .last /** The mapping from the integer used to identify values to the actual * values. */ @@ -112,7 +116,7 @@ abstract class Enumeration (initial: Int) extends Serializable { /** The mapping from the integer used to identify values to their * names. */ - private[this] val nmap: mutable.Map[Int, String] = new mutable.HashMap + private val nmap: mutable.Map[Int, String] = new mutable.HashMap /** The values of this enumeration as a set. */ @@ -128,18 +132,18 @@ abstract class Enumeration (initial: Int) extends Serializable { protected var nextId: Int = initial /** The string to use to name the next created value. */ - protected var nextName: Iterator[String] = _ + protected var nextName: Iterator[String] = compiletime.uninitialized private def nextNameOrNull: String | Null = if (nextName != null && nextName.hasNext) nextName.next() else null /** The highest integer amongst those used to identify values in this * enumeration. */ - private[this] var topId = initial + private var topId = initial /** The lowest integer amongst those used to identify values in this * enumeration, but no higher than 0. */ - private[this] var bottomId = if(initial < 0) initial else 0 + private var bottomId = if(initial < 0) initial else 0 /** The one higher than the highest integer amongst those used to identify * values in this enumeration. */ @@ -190,7 +194,7 @@ abstract class Enumeration (initial: Int) extends Serializable { protected final def Value(i: Int, name: String | Null): Value = new Val(i, name) private def populateNameMap(): Unit = { - @tailrec def getFields(clazz: Class[_] | Null, acc: Array[JField]): Array[JField] = { + @tailrec def getFields(clazz: Class[?] | Null, acc: Array[JField]): Array[JField] = { if (clazz == null) acc else @@ -285,7 +289,7 @@ abstract class Enumeration (initial: Int) extends Serializable { * @define Coll `collection.immutable.SortedSet` */ @SerialVersionUID(7229671200427364242L) - class ValueSet private[ValueSet] (private[this] var nnIds: immutable.BitSet) + class ValueSet private[ValueSet] (private var nnIds: immutable.BitSet) extends immutable.AbstractSet[Value] with immutable.SortedSet[Value] with immutable.SortedSetOps[Value, immutable.SortedSet, ValueSet] @@ -341,7 +345,7 @@ abstract class Enumeration (initial: Int) extends Serializable { def fromBitMask(elems: Array[Long]): ValueSet = new ValueSet(immutable.BitSet.fromBitMask(elems)) /** A builder object for value sets */ def newBuilder: mutable.Builder[Value, ValueSet] = new mutable.Builder[Value, ValueSet] { - private[this] val b = new mutable.BitSet + private val b = new mutable.BitSet def addOne (x: Value) = { b += (x.id - bottomId); this } def clear() = b.clear() def result() = new ValueSet(b.toImmutable) diff --git a/library/src/scala/MatchError.scala b/library/src/scala/MatchError.scala index 2053d2cc6f9c..bbbb929d91d3 100644 --- a/library/src/scala/MatchError.scala +++ b/library/src/scala/MatchError.scala @@ -22,7 +22,7 @@ final class MatchError(@transient obj: Any) extends RuntimeException { /** There's no reason we need to call toString eagerly, * so defer it until getMessage is called or object is serialized */ - private[this] lazy val objString: String = { + private lazy val objString: String = { def ofClass = "of class " + obj.getClass.getName if (obj == null) "null" else diff --git a/library/src/scala/PartialFunction.scala b/library/src/scala/PartialFunction.scala index 31f3fbe77a83..d1f2b7620985 100644 --- a/library/src/scala/PartialFunction.scala +++ b/library/src/scala/PartialFunction.scala @@ -16,6 +16,8 @@ import scala.language.`2.13` import scala.annotation.nowarn import language.experimental.captureChecking +import scala.util.boundary +import scala.util.boundary.break /** A partial function of type `PartialFunction[A, B]` is a unary function * where the domain does not necessarily include all values of type `A`. @@ -262,12 +264,12 @@ trait PartialFunction[-A, +B] extends Function1[A, B] { self: PartialFunction[A, object PartialFunction { final class ElementWiseExtractor[-A, +B] private[PartialFunction] (private val pf: PartialFunction[A, B]^) extends AnyVal { this: ElementWiseExtractor[A, B]^ => - @nowarn("cat=lint-nonlocal-return") def unapplySeq(seq: Seq[A]): Option[Seq[B]] = { - Some(seq.map { - case pf(b) => b - case _ => return None - }) + boundary: + Some(seq.map: + case pf(b) => b + case _ => boundary.break(None) + ) } } @@ -341,7 +343,7 @@ object PartialFunction { * * Here `fallback_fn` is used as both unique marker object and special fallback function that returns it. */ - private[this] val fallback_fn: Any -> Any = _ => fallback_fn + private val fallback_fn: Any -> Any = _ => fallback_fn private def checkFallback[B] = fallback_fn.asInstanceOf[Any => B] private def fallbackOccurred[B](x: B) = fallback_fn eq x.asInstanceOf[AnyRef] @@ -376,9 +378,9 @@ object PartialFunction { */ def fromFunction[A, B](f: A => B): PartialFunction[A, B]^{f} = { case x => f(x) } - private[this] val constFalse: Any -> Boolean = { _ => false} + private val constFalse: Any -> Boolean = { _ => false} - private[this] val empty_pf: PartialFunction[Any, Nothing] = new PartialFunction[Any, Nothing] with Serializable { + private val empty_pf: PartialFunction[Any, Nothing] = new PartialFunction[Any, Nothing] with Serializable { def isDefinedAt(x: Any) = false def apply(x: Any) = throw new MatchError(x) override def orElse[A1, B1](that: PartialFunction[A1, B1]^) = that diff --git a/library/src/scala/Predef.scala b/library/src/scala/Predef.scala index 48030f2f1232..0a336777d179 100644 --- a/library/src/scala/Predef.scala +++ b/library/src/scala/Predef.scala @@ -498,7 +498,7 @@ object Predef extends LowPriorityImplicits { * @see [[scala.StringContext.f StringContext.f]] * @group console-output */ - def printf(text: String, xs: Any*): Unit = Console.print(text.format(xs: _*)) + def printf(text: String, xs: Any*): Unit = Console.print(text.format(xs*)) // views -------------------------------------------------------------- diff --git a/library/src/scala/Product.scala b/library/src/scala/Product.scala index 3ef4e497932a..c8e76c2d8d56 100644 --- a/library/src/scala/Product.scala +++ b/library/src/scala/Product.scala @@ -38,8 +38,8 @@ transparent trait Product extends Any with Equals { * @return in the default implementation, an `Iterator[Any]` */ def productIterator: Iterator[Any] = new scala.collection.AbstractIterator[Any] { - private[this] var c: Int = 0 - private[this] val cmax = productArity + private var c: Int = 0 + private val cmax = productArity def hasNext: Boolean = c < cmax def next(): Any = { val result = productElement(c); c += 1; result } } @@ -66,8 +66,8 @@ transparent trait Product extends Any with Equals { /** An iterator over the names of all the elements of this product. */ def productElementNames: Iterator[String] = new scala.collection.AbstractIterator[String] { - private[this] var c: Int = 0 - private[this] val cmax = productArity + private var c: Int = 0 + private val cmax = productArity def hasNext: Boolean = c < cmax def next(): String = { val result = productElementName(c); c += 1; result } } diff --git a/library/src/scala/Proxy.scala b/library/src/scala/Proxy.scala index d92f10b50c25..5d70bc3bdd10 100644 --- a/library/src/scala/Proxy.scala +++ b/library/src/scala/Proxy.scala @@ -34,7 +34,7 @@ trait Proxy extends Any { case null => false case _ => val x = that.asInstanceOf[AnyRef] - (x eq this.asInstanceOf[AnyRef]) || (x eq self.asInstanceOf[AnyRef]) || (x equals self) + (x eq this.asInstanceOf[AnyRef]) || (x eq self.asInstanceOf[AnyRef]) || (x.equals(self)) } override def toString = "" + self } diff --git a/library/src/scala/ScalaReflectionException.scala b/library/src/scala/ScalaReflectionException.scala new file mode 100644 index 000000000000..9a36ad305488 --- /dev/null +++ b/library/src/scala/ScalaReflectionException.scala @@ -0,0 +1,9 @@ +package scala + +import scala.language.`2.13` + +/** An exception that indicates an error during Scala reflection */ +case class ScalaReflectionException(msg: String) extends Exception(msg) + +object ScalaReflectionException extends scala.runtime.AbstractFunction1[String, ScalaReflectionException]: + override def toString: String = "ScalaReflectionException" diff --git a/library/src/scala/StringContext.scala b/library/src/scala/StringContext.scala index ab07a50d6e01..8dbcdcf03639 100644 --- a/library/src/scala/StringContext.scala +++ b/library/src/scala/StringContext.scala @@ -313,7 +313,7 @@ object StringContext { s"""invalid unicode escape at index $index of $str""" ) - private[this] def readUEscape(src: String, startindex: Int): (Char, Int) = { + private def readUEscape(src: String, startindex: Int): (Char, Int) = { val len = src.length() def loop(uindex: Int): (Char, Int) = { def loopCP(dindex: Int, codepoint: Int): (Char, Int) = { @@ -362,19 +362,19 @@ object StringContext { * @return The string with all escape sequences expanded. */ def processEscapes(str: String): String = - str indexOf '\\' match { + str.indexOf('\\') match { case -1 => str case i => replace(str, i) } protected[scala] def processUnicode(str: String): String = - str indexOf "\\u" match { + str.indexOf("\\u") match { case -1 => str case i => replaceU(str, i) } //replace escapes with given first escape - private[this] def replace(str: String, first: Int): String = { + private def replace(str: String, first: Int): String = { val len = str.length() val b = new JLSBuilder // append replacement starting at index `i`, with `next` backslash @@ -399,7 +399,7 @@ object StringContext { val (ch, advance) = if (c == 'u') readUEscape(str, idx) else (c, 1) idx += advance - b append ch + b.append(ch) loop(idx, str.indexOf('\\', idx)) } else { if (i < len) b.append(str, i, len) @@ -423,7 +423,7 @@ object StringContext { * Otherwise, the backslash is not taken to introduce an escape and the * backslash is taken to be literal */ - private[this] def replaceU(str: String, backslash: Int): String = { + private def replaceU(str: String, backslash: Int): String = { val len = str.length() val b = new JLSBuilder @@ -458,8 +458,8 @@ object StringContext { val ai = args.iterator val bldr = new JLSBuilder(process(pi.next())) while (ai.hasNext) { - bldr append ai.next() - bldr append process(pi.next()) + bldr.append(ai.next()) + bldr.append(process(pi.next())) } bldr.toString } diff --git a/library/src/scala/Symbol.scala b/library/src/scala/Symbol.scala index 922082cc0f62..a61c366f4ae2 100644 --- a/library/src/scala/Symbol.scala +++ b/library/src/scala/Symbol.scala @@ -41,10 +41,10 @@ private[scala] abstract class UniquenessCache[K, V] { import java.util.WeakHashMap import java.util.concurrent.locks.ReentrantReadWriteLock - private[this] val rwl = new ReentrantReadWriteLock() - private[this] val rlock = rwl.readLock - private[this] val wlock = rwl.writeLock - private[this] val map = new WeakHashMap[K, WeakReference[V]] + private val rwl = new ReentrantReadWriteLock() + private val rlock = rwl.readLock + private val wlock = rwl.writeLock + private val map = new WeakHashMap[K, WeakReference[V]] protected def valueFromKey(k: K): V protected def keyFromValue(v: V): Option[K] @@ -53,7 +53,7 @@ private[scala] abstract class UniquenessCache[K, V] { def cached(): V | Null = { rlock.lock try { - val reference = map get name + val reference = map.get(name) if (reference == null) null else reference.get // will be null if we were gc-ed } @@ -69,7 +69,7 @@ private[scala] abstract class UniquenessCache[K, V] { // wind up with one String as the key and a different String as // the name field in the Symbol, which can lead to surprising GC // behavior and duplicate Symbols. See scala/bug#6706. - map remove name + map.remove(name) val sym = valueFromKey(name) map.put(name, new WeakReference(sym)) sym diff --git a/library/src/scala/collection/ArrayOps.scala b/library/src/scala/collection/ArrayOps.scala index 056dd1e9e5c2..11078a63bbbd 100644 --- a/library/src/scala/collection/ArrayOps.scala +++ b/library/src/scala/collection/ArrayOps.scala @@ -125,8 +125,8 @@ object ArrayOps { @SerialVersionUID(3L) private[collection] final class ArrayIterator[@specialized(Specializable.Everything) A](xs: Array[A]) extends AbstractIterator[A] with Serializable { - private[this] var pos = 0 - private[this] val len = xs.length + private var pos = 0 + private val len = xs.length override def knownSize: Int = len - pos def hasNext: Boolean = pos < len def next(): A = { @@ -148,7 +148,7 @@ object ArrayOps { @SerialVersionUID(3L) private final class ReverseIterator[@specialized(Specializable.Everything) A](xs: Array[A]) extends AbstractIterator[A] with Serializable { - private[this] var pos = xs.length-1 + private var pos = xs.length-1 def hasNext: Boolean = pos >= 0 def next(): A = { if (pos < 0) Iterator.empty.next() @@ -165,7 +165,7 @@ object ArrayOps { @SerialVersionUID(3L) private final class GroupedIterator[A](xs: Array[A], groupSize: Int) extends AbstractIterator[Array[A]] with Serializable { - private[this] var pos = 0 + private var pos = 0 def hasNext: Boolean = pos < xs.length def next(): Array[A] = { if(pos >= xs.length) throw new NoSuchElementException @@ -202,7 +202,7 @@ object ArrayOps { */ final class ArrayOps[A](private val xs: Array[A]) extends AnyVal { - @`inline` private[this] implicit def elemTag: ClassTag[A] = ClassTag(xs.getClass.getComponentType) + @`inline` private implicit def elemTag: ClassTag[A] = ClassTag(xs.getClass.getComponentType) /** The size of this array. * @@ -331,7 +331,7 @@ final class ArrayOps[A](private val xs: Array[A]) extends AnyVal { val lo = max(from, 0) val hi = min(until, xs.length) if (hi > lo) { - (((xs: Array[_]): @unchecked) match { + (((xs: Array[?]): @unchecked) match { case x: Array[AnyRef] => copyOfRange(x, lo, hi) case x: Array[Int] => copyOfRange(x, lo, hi) case x: Array[Double] => copyOfRange(x, lo, hi) @@ -370,7 +370,7 @@ final class ArrayOps[A](private val xs: Array[A]) extends AnyVal { def inits: Iterator[Array[A]] = iterateUntilEmpty(xs => new ArrayOps(xs).init) // A helper for tails and inits. - private[this] def iterateUntilEmpty(f: Array[A] => Array[A]): Iterator[Array[A]]^{f} = + private def iterateUntilEmpty(f: Array[A] => Array[A]): Iterator[Array[A]]^{f} = Iterator.iterate(xs)(f).takeWhile(x => x.length != 0) ++ Iterator.single(Array.empty[A]) /** An array containing the first `n` elements of this array. */ @@ -424,7 +424,7 @@ final class ArrayOps[A](private val xs: Array[A]) extends AnyVal { case null => throw new NullPointerException }).asInstanceOf[Iterator[A]] - def stepper[S <: Stepper[_]](implicit shape: StepperShape[A, S]): S with EfficientSplit = { + def stepper[S <: Stepper[?]](implicit shape: StepperShape[A, S]): S & EfficientSplit = { import convert.impl._ val s = (shape.shape: @unchecked) match { case StepperShape.ReferenceShape => (xs: Any) match { @@ -439,7 +439,7 @@ final class ArrayOps[A](private val xs: Array[A]) extends AnyVal { case StepperShape.CharShape => new WidenedCharArrayStepper (xs.asInstanceOf[Array[Char ]], 0, xs.length) case StepperShape.FloatShape => new WidenedFloatArrayStepper (xs.asInstanceOf[Array[Float ]], 0, xs.length) } - s.asInstanceOf[S with EfficientSplit] + s.asInstanceOf[S & EfficientSplit] } /** Partitions elements in fixed size arrays. @@ -596,12 +596,12 @@ final class ArrayOps[A](private val xs: Array[A]) extends AnyVal { Sorting.stableSort(a)(using ord.asInstanceOf[Ordering[A]]) a } else { - val a = Array.copyAs[AnyRef](xs, len)(ClassTag.AnyRef) + val a = Array.copyAs[AnyRef](xs, len)(using ClassTag.AnyRef) Arrays.sort(a, ord.asInstanceOf[Ordering[AnyRef]]) Array.copyAs[A](a, len) } if(len <= 1) xs.clone() - else ((xs: Array[_]) match { + else ((xs: Array[?]) match { case xs: Array[AnyRef] => val a = Arrays.copyOf(xs, len); Arrays.sort(a, ord.asInstanceOf[Ordering[AnyRef]]); a case xs: Array[Int] => @@ -637,7 +637,7 @@ final class ArrayOps[A](private val xs: Array[A]) extends AnyVal { * @return an array consisting of the elements of this array * sorted according to the comparison function `lt`. */ - def sortWith(lt: (A, A) => Boolean): Array[A] = sorted(Ordering.fromLessThan(lt)) + def sortWith(lt: (A, A) => Boolean): Array[A] = sorted(using Ordering.fromLessThan(lt)) /** Sorts this array according to the Ordering which results from transforming * an implicitly given Ordering with a transformation function. @@ -652,7 +652,7 @@ final class ArrayOps[A](private val xs: Array[A]) extends AnyVal { * sorted according to the ordering where `x < y` if * `ord.lt(f(x), f(y))`. */ - def sortBy[B](f: A => B)(implicit ord: Ordering[B]): Array[A] = sorted(ord on f) + def sortBy[B](f: A => B)(implicit ord: Ordering[B]): Array[A] = sorted(using ord.on(f)) /** Creates a non-strict filter of this array. * @@ -1166,7 +1166,7 @@ final class ArrayOps[A](private val xs: Array[A]) extends AnyVal { } /** A copy of this array with all elements of an array prepended. */ - def prependedAll[B >: A : ClassTag](prefix: Array[_ <: B]): Array[B] = { + def prependedAll[B >: A : ClassTag](prefix: Array[? <: B]): Array[B] = { val dest = Array.copyAs[B](prefix, prefix.length+xs.length) Array.copy(xs, 0, dest, prefix.length, xs.length) dest @@ -1174,7 +1174,7 @@ final class ArrayOps[A](private val xs: Array[A]) extends AnyVal { @`inline` final def ++: [B >: A : ClassTag](prefix: IterableOnce[B]^): Array[B] = prependedAll(prefix) - @`inline` final def ++: [B >: A : ClassTag](prefix: Array[_ <: B]): Array[B] = prependedAll(prefix) + @`inline` final def ++: [B >: A : ClassTag](prefix: Array[? <: B]): Array[B] = prependedAll(prefix) /** A copy of this array with all elements of a collection appended. */ def appendedAll[B >: A : ClassTag](suffix: IterableOnce[B]^): Array[B] = { @@ -1186,7 +1186,7 @@ final class ArrayOps[A](private val xs: Array[A]) extends AnyVal { } /** A copy of this array with all elements of an array appended. */ - def appendedAll[B >: A : ClassTag](suffix: Array[_ <: B]): Array[B] = { + def appendedAll[B >: A : ClassTag](suffix: Array[? <: B]): Array[B] = { val dest = Array.copyAs[B](xs, xs.length+suffix.length) Array.copy(suffix, 0, dest, xs.length, suffix.length) dest @@ -1194,15 +1194,15 @@ final class ArrayOps[A](private val xs: Array[A]) extends AnyVal { @`inline` final def :++ [B >: A : ClassTag](suffix: IterableOnce[B]^): Array[B] = appendedAll(suffix) - @`inline` final def :++ [B >: A : ClassTag](suffix: Array[_ <: B]): Array[B] = appendedAll(suffix) + @`inline` final def :++ [B >: A : ClassTag](suffix: Array[? <: B]): Array[B] = appendedAll(suffix) @`inline` final def concat[B >: A : ClassTag](suffix: IterableOnce[B]^): Array[B] = appendedAll(suffix) - @`inline` final def concat[B >: A : ClassTag](suffix: Array[_ <: B]): Array[B] = appendedAll(suffix) + @`inline` final def concat[B >: A : ClassTag](suffix: Array[? <: B]): Array[B] = appendedAll(suffix) @`inline` final def ++[B >: A : ClassTag](xs: IterableOnce[B]^): Array[B] = appendedAll(xs) - @`inline` final def ++[B >: A : ClassTag](xs: Array[_ <: B]): Array[B] = appendedAll(xs) + @`inline` final def ++[B >: A : ClassTag](xs: Array[? <: B]): Array[B] = appendedAll(xs) /** Tests whether this array contains a given value as an element. * @@ -1300,7 +1300,7 @@ final class ArrayOps[A](private val xs: Array[A]) extends AnyVal { */ def transpose[B](implicit asArray: A => Array[B]): Array[Array[B]] = { val aClass = xs.getClass.getComponentType - val bb = new ArrayBuilder.ofRef[Array[B]]()(ClassTag[Array[B]](aClass)) + val bb = new ArrayBuilder.ofRef[Array[B]]()(using ClassTag[Array[B]](aClass)) if (xs.length == 0) bb.result() else { def mkRowBuilder() = ArrayBuilder.make[B](using ClassTag[B](aClass.getComponentType)) diff --git a/library/src/scala/collection/BitSet.scala b/library/src/scala/collection/BitSet.scala index dc3d3b7ab7e7..4a44175fb700 100644 --- a/library/src/scala/collection/BitSet.scala +++ b/library/src/scala/collection/BitSet.scala @@ -40,7 +40,7 @@ trait BitSet extends SortedSet[Int] with BitSetOps[BitSet] { self: BitSet => override protected def newSpecificBuilder: Builder[Int, BitSet] = bitSetFactory.newBuilder override def empty: BitSet = bitSetFactory.empty @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix = "BitSet" + override protected def stringPrefix = "BitSet" override def unsorted: Set[Int] = this } @@ -56,9 +56,9 @@ object BitSet extends SpecificIterableFactory[Int, BitSet] { @SerialVersionUID(3L) private[collection] abstract class SerializationProxy(@transient protected val coll: BitSet) extends Serializable { - @transient protected var elems: Array[Long] = _ + @transient protected var elems: Array[Long] = compiletime.uninitialized - private[this] def writeObject(out: ObjectOutputStream): Unit = { + private def writeObject(out: ObjectOutputStream): Unit = { out.defaultWriteObject() val nwords = coll.nwords out.writeInt(nwords) @@ -69,7 +69,7 @@ object BitSet extends SpecificIterableFactory[Int, BitSet] { } } - private[this] def readObject(in: ObjectInputStream): Unit = { + private def readObject(in: ObjectInputStream): Unit = { in.defaultReadObject() val nwords = in.readInt() elems = new Array[Long](nwords) @@ -80,12 +80,12 @@ object BitSet extends SpecificIterableFactory[Int, BitSet] { } } - protected[this] def readResolve(): Any + protected def readResolve(): Any } } /** Base implementation type of bitsets */ -transparent trait BitSetOps[+C <: BitSet with BitSetOps[C]] +transparent trait BitSetOps[+C <: BitSet & BitSetOps[C]] extends SortedSetOps[Int, SortedSet, C] { self => import BitSetOps._ @@ -113,8 +113,8 @@ transparent trait BitSetOps[+C <: BitSet with BitSetOps[C]] def iterator: Iterator[Int] = iteratorFrom(0) def iteratorFrom(start: Int): Iterator[Int] = new AbstractIterator[Int] { - private[this] var currentPos = if (start > 0) start >> LogWL else 0 - private[this] var currentWord = if (start > 0) word(currentPos) & (-1L << (start & (WordLength - 1))) else word(0) + private var currentPos = if (start > 0) start >> LogWL else 0 + private var currentWord = if (start > 0) word(currentPos) & (-1L << (start & (WordLength - 1))) else word(0) final override def hasNext: Boolean = { while (currentWord == 0) { if (currentPos + 1 >= nwords) return false @@ -132,7 +132,7 @@ transparent trait BitSetOps[+C <: BitSet with BitSetOps[C]] } } - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[Int, S]): S with EfficientSplit = { + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[Int, S]): S & EfficientSplit = { val st = scala.collection.convert.impl.BitSetStepper.from(this) val r = if (shape.shape == StepperShape.IntShape) st @@ -140,7 +140,7 @@ transparent trait BitSetOps[+C <: BitSet with BitSetOps[C]] assert(shape.shape == StepperShape.ReferenceShape, s"unexpected StepperShape: $shape") AnyStepper.ofParIntStepper(st) } - r.asInstanceOf[S with EfficientSplit] + r.asInstanceOf[S & EfficientSplit] } override def size: Int = { @@ -155,7 +155,7 @@ transparent trait BitSetOps[+C <: BitSet with BitSetOps[C]] override def isEmpty: Boolean = 0 until nwords forall (i => word(i) == 0) - @inline private[this] def smallestInt: Int = { + @inline private def smallestInt: Int = { val thisnwords = nwords var i = 0 while(i < thisnwords) { @@ -168,7 +168,7 @@ transparent trait BitSetOps[+C <: BitSet with BitSetOps[C]] throw new UnsupportedOperationException("empty.smallestInt") } - @inline private[this] def largestInt: Int = { + @inline private def largestInt: Int = { var i = nwords - 1 while(i >= 0) { val currentWord = word(i) @@ -183,13 +183,13 @@ transparent trait BitSetOps[+C <: BitSet with BitSetOps[C]] override def max[B >: Int](implicit ord: Ordering[B]): Int = if (Ordering.Int eq ord) largestInt else if (Ordering.Int isReverseOf ord) smallestInt - else super.max(ord) + else super.max(using ord) override def min[B >: Int](implicit ord: Ordering[B]): Int = if (Ordering.Int eq ord) smallestInt else if (Ordering.Int isReverseOf ord) largestInt - else super.min(ord) + else super.min(using ord) override def foreach[U](f: Int => U): Unit = { /* NOTE: while loops are significantly faster as of 2.11 and diff --git a/library/src/scala/collection/BuildFrom.scala b/library/src/scala/collection/BuildFrom.scala index 8ee65badf1a4..cb819db200ec 100644 --- a/library/src/scala/collection/BuildFrom.scala +++ b/library/src/scala/collection/BuildFrom.scala @@ -48,19 +48,19 @@ trait BuildFrom[-From, -A, +C] extends Any { self => object BuildFrom extends BuildFromLowPriority1 { /** Build the source collection type from a MapOps */ - implicit def buildFromMapOps[CC[X, Y] <: Map[X, Y] with MapOps[X, Y, CC, _], K0, V0, K, V]: BuildFrom[CC[K0, V0] with Map[K0, V0], (K, V), CC[K, V] with Map[K, V]] = new BuildFrom[CC[K0, V0], (K, V), CC[K, V]] { + implicit def buildFromMapOps[CC[X, Y] <: Map[X, Y] & MapOps[X, Y, CC, ?], K0, V0, K, V]: BuildFrom[CC[K0, V0] & Map[K0, V0], (K, V), CC[K, V] & Map[K, V]] = new BuildFrom[CC[K0, V0], (K, V), CC[K, V]] { //TODO: Reuse a prototype instance - def newBuilder(from: CC[K0, V0]): Builder[(K, V), CC[K, V]] = (from: MapOps[K0, V0, CC, _]).mapFactory.newBuilder[K, V] - def fromSpecific(from: CC[K0, V0])(it: IterableOnce[(K, V)]^): CC[K, V] = (from: MapOps[K0, V0, CC, _]).mapFactory.from(it) + def newBuilder(from: CC[K0, V0]): Builder[(K, V), CC[K, V]] = (from: MapOps[K0, V0, CC, ?]).mapFactory.newBuilder[K, V] + def fromSpecific(from: CC[K0, V0])(it: IterableOnce[(K, V)]^): CC[K, V] = (from: MapOps[K0, V0, CC, ?]).mapFactory.from(it) } /** Build the source collection type from a SortedMapOps */ - implicit def buildFromSortedMapOps[CC[X, Y] <: SortedMap[X, Y] with SortedMapOps[X, Y, CC, _], K0, V0, K : Ordering, V]: BuildFrom[CC[K0, V0] with SortedMap[K0, V0], (K, V), CC[K, V] with SortedMap[K, V]] = new BuildFrom[CC[K0, V0], (K, V), CC[K, V]] { - def newBuilder(from: CC[K0, V0]): Builder[(K, V), CC[K, V]] = (from: SortedMapOps[K0, V0, CC, _]).sortedMapFactory.newBuilder[K, V] - def fromSpecific(from: CC[K0, V0])(it: IterableOnce[(K, V)]^): CC[K, V] = (from: SortedMapOps[K0, V0, CC, _]).sortedMapFactory.from(it) + implicit def buildFromSortedMapOps[CC[X, Y] <: SortedMap[X, Y] & SortedMapOps[X, Y, CC, ?], K0, V0, K : Ordering, V]: BuildFrom[CC[K0, V0] & SortedMap[K0, V0], (K, V), CC[K, V] & SortedMap[K, V]] = new BuildFrom[CC[K0, V0], (K, V), CC[K, V]] { + def newBuilder(from: CC[K0, V0]): Builder[(K, V), CC[K, V]] = (from: SortedMapOps[K0, V0, CC, ?]).sortedMapFactory.newBuilder[K, V] + def fromSpecific(from: CC[K0, V0])(it: IterableOnce[(K, V)]^): CC[K, V] = (from: SortedMapOps[K0, V0, CC, ?]).sortedMapFactory.from(it) } - implicit def buildFromBitSet[C <: BitSet with BitSetOps[C]]: BuildFrom[C, Int, C] = + implicit def buildFromBitSet[C <: BitSet & BitSetOps[C]]: BuildFrom[C, Int, C] = new BuildFrom[C, Int, C] { def fromSpecific(from: C)(it: IterableOnce[Int]^): C = from.bitSetFactory.fromSpecific(it) def newBuilder(from: C): Builder[Int, C] = from.bitSetFactory.newBuilder @@ -78,10 +78,10 @@ object BuildFrom extends BuildFromLowPriority1 { def newBuilder(from: WrappedString): mutable.Builder[Char, WrappedString] = WrappedString.newBuilder } - implicit def buildFromArray[A : ClassTag]: BuildFrom[Array[_], A, Array[A]] = - new BuildFrom[Array[_], A, Array[A]] { - def fromSpecific(from: Array[_])(it: IterableOnce[A]^): Array[A] = Factory.arrayFactory[A].fromSpecific(it) - def newBuilder(from: Array[_]): Builder[A, Array[A]] = Factory.arrayFactory[A].newBuilder + implicit def buildFromArray[A : ClassTag]: BuildFrom[Array[?], A, Array[A]] = + new BuildFrom[Array[?], A, Array[A]] { + def fromSpecific(from: Array[?])(it: IterableOnce[A]^): Array[A] = Factory.arrayFactory[A].fromSpecific(it) + def newBuilder(from: Array[?]): Builder[A, Array[A]] = Factory.arrayFactory[A].newBuilder } implicit def buildFromView[A, B]: BuildFrom[View[A], B, View[B]] = @@ -98,9 +98,9 @@ trait BuildFromLowPriority1 extends BuildFromLowPriority2 { // Restating the upper bound of CC in the result type seems redundant, but it serves to prune the // implicit search space for faster compilation and reduced change of divergence. See the compilation // test in test/junit/scala/collection/BuildFromTest.scala and discussion in https://github.com/scala/scala/pull/10209 - implicit def buildFromSortedSetOps[CC[X] <: SortedSet[X] with SortedSetOps[X, CC, _], A0, A : Ordering]: BuildFrom[CC[A0] with SortedSet[A0], A, CC[A] with SortedSet[A]] = new BuildFrom[CC[A0], A, CC[A]] { - def newBuilder(from: CC[A0]): Builder[A, CC[A]] = (from: SortedSetOps[A0, CC, _]).sortedIterableFactory.newBuilder[A] - def fromSpecific(from: CC[A0])(it: IterableOnce[A]^): CC[A] = (from: SortedSetOps[A0, CC, _]).sortedIterableFactory.from(it) + implicit def buildFromSortedSetOps[CC[X] <: SortedSet[X] & SortedSetOps[X, CC, ?], A0, A : Ordering]: BuildFrom[CC[A0] & SortedSet[A0], A, CC[A] & SortedSet[A]] = new BuildFrom[CC[A0], A, CC[A]] { + def newBuilder(from: CC[A0]): Builder[A, CC[A]] = (from: SortedSetOps[A0, CC, ?]).sortedIterableFactory.newBuilder[A] + def fromSpecific(from: CC[A0])(it: IterableOnce[A]^): CC[A] = (from: SortedSetOps[A0, CC, ?]).sortedIterableFactory.from(it) } implicit def fallbackStringCanBuildFrom[A]: BuildFrom[String, A, immutable.IndexedSeq[A]] = @@ -112,14 +112,14 @@ trait BuildFromLowPriority1 extends BuildFromLowPriority2 { trait BuildFromLowPriority2 { /** Build the source collection type from an IterableOps */ - implicit def buildFromIterableOps[CC[X] <: Iterable[X] with IterableOps[X, CC, _], A0, A]: BuildFrom[CC[A0], A, CC[A]] = new BuildFrom[CC[A0], A, CC[A]] { + implicit def buildFromIterableOps[CC[X] <: Iterable[X] & IterableOps[X, CC, ?], A0, A]: BuildFrom[CC[A0], A, CC[A]] = new BuildFrom[CC[A0], A, CC[A]] { //TODO: Reuse a prototype instance - def newBuilder(from: CC[A0]): Builder[A, CC[A]] = (from: IterableOps[A0, CC, _]).iterableFactory.newBuilder[A] - def fromSpecific(from: CC[A0])(it: IterableOnce[A]^): CC[A]^{it} = (from: IterableOps[A0, CC, _]).iterableFactory.from(it) + def newBuilder(from: CC[A0]): Builder[A, CC[A]] = (from: IterableOps[A0, CC, ?]).iterableFactory.newBuilder[A] + def fromSpecific(from: CC[A0])(it: IterableOnce[A]^): CC[A]^{it} = (from: IterableOps[A0, CC, ?]).iterableFactory.from(it) } - implicit def buildFromIterator[A]: BuildFrom[Iterator[_], A, Iterator[A]] = new BuildFrom[Iterator[_], A, Iterator[A]] { - def newBuilder(from: Iterator[_]): mutable.Builder[A, Iterator[A]] = Iterator.newBuilder - def fromSpecific(from: Iterator[_])(it: IterableOnce[A]^): Iterator[A]^{it} = Iterator.from(it) + implicit def buildFromIterator[A]: BuildFrom[Iterator[?], A, Iterator[A]] = new BuildFrom[Iterator[?], A, Iterator[A]] { + def newBuilder(from: Iterator[?]): mutable.Builder[A, Iterator[A]] = Iterator.newBuilder + def fromSpecific(from: Iterator[?])(it: IterableOnce[A]^): Iterator[A]^{it} = Iterator.from(it) } } diff --git a/library/src/scala/collection/Factory.scala b/library/src/scala/collection/Factory.scala index 2d335af7029d..7e7e0d945e3d 100644 --- a/library/src/scala/collection/Factory.scala +++ b/library/src/scala/collection/Factory.scala @@ -273,7 +273,7 @@ object IterableFactory { implicit def toFactory[A, CC[_]](factory: IterableFactory[CC]): Factory[A, CC[A]] = new ToFactory[A, CC](factory) @SerialVersionUID(3L) - private[this] class ToFactory[A, CC[_]](factory: IterableFactory[CC]) extends Factory[A, CC[A]] with Serializable { + private class ToFactory[A, CC[_]](factory: IterableFactory[CC]) extends Factory[A, CC[A]] with Serializable { def fromSpecific(it: IterableOnce[A]^): CC[A]^{it} = factory.from[A](it) def newBuilder: Builder[A, CC[A]] = factory.newBuilder[A] } @@ -286,7 +286,7 @@ object IterableFactory { @SerialVersionUID(3L) class Delegate[CC[_]](delegate: IterableFactory[CC]) extends IterableFactory[CC] { - override def apply[A](elems: A*): CC[A] = delegate.apply(elems: _*) + override def apply[A](elems: A*): CC[A] = delegate.apply(elems*) def empty[A]: CC[A] = delegate.empty def from[E](it: IterableOnce[E]^): CC[E]^{it} = delegate.from(it) def newBuilder[A]: Builder[A, CC[A]] = delegate.newBuilder[A] @@ -304,7 +304,7 @@ trait SeqFactory[+CC[A] <: SeqOps[A, Seq, Seq[A]] & caps.Pure] extends IterableF object SeqFactory { @SerialVersionUID(3L) class Delegate[CC[A] <: SeqOps[A, Seq, Seq[A]] & caps.Pure](delegate: SeqFactory[CC]) extends SeqFactory[CC] { - override def apply[A](elems: A*): CC[A] = delegate.apply(elems: _*) + override def apply[A](elems: A*): CC[A] = delegate.apply(elems*) def empty[A]: CC[A] = delegate.empty def from[E](it: IterableOnce[E]^): CC[E] = delegate.from(it) def newBuilder[A]: Builder[A, CC[A]] = delegate.newBuilder[A] @@ -426,7 +426,7 @@ object MapFactory { implicit def toFactory[K, V, CC[_, _]](factory: MapFactory[CC]): Factory[(K, V), CC[K, V]] = new ToFactory[K, V, CC](factory) @SerialVersionUID(3L) - private[this] class ToFactory[K, V, CC[_, _]](factory: MapFactory[CC]) extends Factory[(K, V), CC[K, V]] with Serializable { + private class ToFactory[K, V, CC[_, _]](factory: MapFactory[CC]) extends Factory[(K, V), CC[K, V]] with Serializable { def fromSpecific(it: IterableOnce[(K, V)]^): CC[K, V]^{it} = factory.from[K, V](it) def newBuilder: Builder[(K, V), CC[K, V]] = factory.newBuilder[K, V] } @@ -439,7 +439,7 @@ object MapFactory { @SerialVersionUID(3L) class Delegate[C[_, _] <: caps.Pure](delegate: MapFactory[C]) extends MapFactory[C] { - override def apply[K, V](elems: (K, V)*): C[K, V] = delegate.apply(elems: _*) + override def apply[K, V](elems: (K, V)*): C[K, V] = delegate.apply(elems*) def from[K, V](it: IterableOnce[(K, V)]^): C[K, V] = delegate.from(it) def empty[K, V]: C[K, V] = delegate.empty def newBuilder[K, V]: Builder[(K, V), C[K, V]] = delegate.newBuilder @@ -519,7 +519,7 @@ object EvidenceIterableFactory { implicit def toFactory[Ev[_], A: Ev, CC[_]](factory: EvidenceIterableFactory[CC, Ev]): Factory[A, CC[A]] = new ToFactory[Ev, A, CC](factory) @SerialVersionUID(3L) - private[this] class ToFactory[Ev[_], A: Ev, CC[_]](factory: EvidenceIterableFactory[CC, Ev]) extends Factory[A, CC[A]] with Serializable { + private class ToFactory[Ev[_], A: Ev, CC[_]](factory: EvidenceIterableFactory[CC, Ev]) extends Factory[A, CC[A]] with Serializable { def fromSpecific(it: IterableOnce[A]^) = factory.from[A](it) def newBuilder: Builder[A, CC[A]] = factory.newBuilder[A] } @@ -532,7 +532,7 @@ object EvidenceIterableFactory { @SerialVersionUID(3L) class Delegate[CC[_], Ev[_]](delegate: EvidenceIterableFactory[CC, Ev]) extends EvidenceIterableFactory[CC, Ev] { - override def apply[A: Ev](xs: A*): CC[A] = delegate.apply(xs: _*) + override def apply[A: Ev](xs: A*): CC[A] = delegate.apply(xs*) def empty[A : Ev]: CC[A] = delegate.empty def from[E : Ev](it: IterableOnce[E]^): CC[E] = delegate.from(it) def newBuilder[A : Ev]: Builder[A, CC[A]] = delegate.newBuilder[A] @@ -555,7 +555,7 @@ object SortedIterableFactory { */ trait ClassTagIterableFactory[+CC[_]] extends EvidenceIterableFactory[CC, ClassTag] { - @`inline` private[this] implicit def ccClassTag[X]: ClassTag[CC[X]] = + @`inline` private implicit def ccClassTag[X]: ClassTag[CC[X]] = ClassTag.AnyRef.asInstanceOf[ClassTag[CC[X]]] // Good enough for boxed vs primitive arrays /** Produces a $coll containing a sequence of increasing of integers. @@ -673,7 +673,7 @@ object ClassTagIterableFactory { def empty[A]: CC[A] = delegate.empty(using ClassTag.Any).asInstanceOf[CC[A]] def from[A](it: IterableOnce[A]^): CC[A] = delegate.from[Any](it)(using ClassTag.Any).asInstanceOf[CC[A]] def newBuilder[A]: Builder[A, CC[A]] = delegate.newBuilder(using ClassTag.Any).asInstanceOf[Builder[A, CC[A]]] - override def apply[A](elems: A*): CC[A] = delegate.apply[Any](elems: _*)(using ClassTag.Any).asInstanceOf[CC[A]] + override def apply[A](elems: A*): CC[A] = delegate.apply[Any](elems*)(using ClassTag.Any).asInstanceOf[CC[A]] override def iterate[A](start: A, len: Int)(f: A => A): CC[A] = delegate.iterate[A](start, len)(f)(using ClassTag.Any.asInstanceOf[ClassTag[A]]) override def unfold[A, S](init: S)(f: S => Option[(A, S)]): CC[A] = delegate.unfold[A, S](init)(f)(using ClassTag.Any.asInstanceOf[ClassTag[A]]) override def range[A](start: A, end: A)(implicit i: Integral[A]): CC[A] = delegate.range[A](start, end)(using i, ClassTag.Any.asInstanceOf[ClassTag[A]]) @@ -766,7 +766,7 @@ object SortedMapFactory { implicit def toFactory[K : Ordering, V, CC[_, _]](factory: SortedMapFactory[CC]): Factory[(K, V), CC[K, V]] = new ToFactory[K, V, CC](factory) @SerialVersionUID(3L) - private[this] class ToFactory[K : Ordering, V, CC[_, _]](factory: SortedMapFactory[CC]) extends Factory[(K, V), CC[K, V]] with Serializable { + private class ToFactory[K : Ordering, V, CC[_, _]](factory: SortedMapFactory[CC]) extends Factory[(K, V), CC[K, V]] with Serializable { def fromSpecific(it: IterableOnce[(K, V)]^): CC[K, V] = factory.from[K, V](it) def newBuilder: Builder[(K, V), CC[K, V]] = factory.newBuilder[K, V] } @@ -779,7 +779,7 @@ object SortedMapFactory { @SerialVersionUID(3L) class Delegate[CC[_, _]](delegate: SortedMapFactory[CC]) extends SortedMapFactory[CC] { - override def apply[K: Ordering, V](elems: (K, V)*): CC[K, V] = delegate.apply(elems: _*) + override def apply[K: Ordering, V](elems: (K, V)*): CC[K, V] = delegate.apply(elems*) def from[K : Ordering, V](it: IterableOnce[(K, V)]^): CC[K, V] = delegate.from(it) def empty[K : Ordering, V]: CC[K, V] = delegate.empty def newBuilder[K : Ordering, V]: Builder[(K, V), CC[K, V]] = delegate.newBuilder diff --git a/library/src/scala/collection/IndexedSeq.scala b/library/src/scala/collection/IndexedSeq.scala index a2c9fcd1bd25..753d036856a7 100644 --- a/library/src/scala/collection/IndexedSeq.scala +++ b/library/src/scala/collection/IndexedSeq.scala @@ -26,7 +26,7 @@ trait IndexedSeq[+A] extends Seq[A] with IndexedSeqOps[A, IndexedSeq, IndexedSeq[A]] with IterableFactoryDefaults[A, IndexedSeq] { @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix: String = "IndexedSeq" + override protected def stringPrefix: String = "IndexedSeq" override def iterableFactory: SeqFactory[IndexedSeq] = IndexedSeq } @@ -39,15 +39,15 @@ transparent trait IndexedSeqOps[+A, +CC[_], +C] extends Any with SeqOps[A, CC, C def iterator: Iterator[A]^{this} = view.iterator - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[A, S]): S with EfficientSplit = { + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[A, S]): S & EfficientSplit = { import convert.impl._ val s = shape.shape match { - case StepperShape.IntShape => new IntIndexedSeqStepper (this.asInstanceOf[IndexedSeqOps[Int, AnyConstr, _]], 0, length) - case StepperShape.LongShape => new LongIndexedSeqStepper (this.asInstanceOf[IndexedSeqOps[Long, AnyConstr, _]], 0, length) - case StepperShape.DoubleShape => new DoubleIndexedSeqStepper(this.asInstanceOf[IndexedSeqOps[Double, AnyConstr, _]], 0, length) + case StepperShape.IntShape => new IntIndexedSeqStepper (this.asInstanceOf[IndexedSeqOps[Int, AnyConstr, ?]], 0, length) + case StepperShape.LongShape => new LongIndexedSeqStepper (this.asInstanceOf[IndexedSeqOps[Long, AnyConstr, ?]], 0, length) + case StepperShape.DoubleShape => new DoubleIndexedSeqStepper(this.asInstanceOf[IndexedSeqOps[Double, AnyConstr, ?]], 0, length) case _ => shape.parUnbox(new AnyIndexedSeqStepper[A](this, 0, length)) } - s.asInstanceOf[S with EfficientSplit] + s.asInstanceOf[S & EfficientSplit] } override def reverseIterator: Iterator[A]^{this} = view.reverseIterator @@ -126,20 +126,20 @@ transparent trait IndexedSeqOps[+A, +CC[_], +C] extends Any with SeqOps[A, CC, C override def knownSize: Int = length - override final def lengthCompare(that: Iterable[_]^): Int = { + override final def lengthCompare(that: Iterable[?]^): Int = { val res = that.sizeCompare(length) // can't just invert the result, because `-Int.MinValue == Int.MinValue` if (res == Int.MinValue) 1 else -res } override def search[B >: A](elem: B)(implicit ord: Ordering[B]): SearchResult = - binarySearch(elem, 0, length)(ord) + binarySearch(elem, 0, length)(using ord) override def search[B >: A](elem: B, from: Int, to: Int)(implicit ord: Ordering[B]): SearchResult = - binarySearch(elem, from, to)(ord) + binarySearch(elem, from, to)(using ord) @tailrec - private[this] def binarySearch[B >: A](elem: B, from: Int, to: Int) + private def binarySearch[B >: A](elem: B, from: Int, to: Int) (implicit ord: Ordering[B]): SearchResult = { if (from < 0) binarySearch(elem, 0, to) else if (to > length) binarySearch(elem, from, length) @@ -147,8 +147,8 @@ transparent trait IndexedSeqOps[+A, +CC[_], +C] extends Any with SeqOps[A, CC, C else { val idx = from + (to - from - 1) / 2 math.signum(ord.compare(elem, apply(idx))) match { - case -1 => binarySearch(elem, from, idx)(ord) - case 1 => binarySearch(elem, idx + 1, to)(ord) + case -1 => binarySearch(elem, from, idx)(using ord) + case 1 => binarySearch(elem, idx + 1, to)(using ord) case _ => Found(idx) } } @@ -161,8 +161,8 @@ private final class IndexedSeqSlidingIterator[A, CC[_], C](s: IndexedSeqOps[A, C // CC note: seems like the compiler cannot figure out that this class <: Iterator[C^{s}], // so we need a cast when upcasting is needed. - private[this] val len = s.length - private[this] var pos = 0 + private val len = s.length + private var pos = 0 private def chklen: Boolean = len == s.length || { throw new java.util.ConcurrentModificationException("collection size changed during iteration") false diff --git a/library/src/scala/collection/IndexedSeqView.scala b/library/src/scala/collection/IndexedSeqView.scala index 545563bb51a0..684440bcbd77 100644 --- a/library/src/scala/collection/IndexedSeqView.scala +++ b/library/src/scala/collection/IndexedSeqView.scala @@ -46,17 +46,17 @@ trait IndexedSeqView[+A] extends IndexedSeqOps[A, View, View[A]] with SeqView[A] def prependedAll[B >: A](prefix: IndexedSeqView.SomeIndexedSeqOps[B]^): IndexedSeqView[B]^{this, prefix} = new IndexedSeqView.Concat(prefix, this) @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix: String = "IndexedSeqView" + override protected def stringPrefix: String = "IndexedSeqView" } object IndexedSeqView { @SerialVersionUID(3L) private[collection] class IndexedSeqViewIterator[A](self: IndexedSeqView[A]^) extends AbstractIterator[A] with Serializable { - private[this] var current = 0 - private[this] var remainder = self.length + private var current = 0 + private var remainder = self.length override def knownSize: Int = remainder - @inline private[this] def _hasNext: Boolean = remainder > 0 + @inline private def _hasNext: Boolean = remainder > 0 def hasNext: Boolean = _hasNext def next(): A = if (_hasNext) { @@ -87,9 +87,9 @@ object IndexedSeqView { } @SerialVersionUID(3L) private[collection] class IndexedSeqViewReverseIterator[A](self: IndexedSeqView[A]^) extends AbstractIterator[A] with Serializable { - private[this] var remainder = self.length - private[this] var pos = remainder - 1 - @inline private[this] def _hasNext: Boolean = remainder > 0 + private var remainder = self.length + private var pos = remainder - 1 + @inline private def _hasNext: Boolean = remainder > 0 def hasNext: Boolean = _hasNext def next(): A = if (_hasNext) { @@ -121,7 +121,7 @@ object IndexedSeqView { } /** An `IndexedSeqOps` whose collection type and collection type constructor are unknown */ - type SomeIndexedSeqOps[A] = IndexedSeqOps[A, AnyConstr, _] + type SomeIndexedSeqOps[A] = IndexedSeqOps[A, AnyConstr, ?] @SerialVersionUID(3L) class Id[+A](underlying: SomeIndexedSeqOps[A]^) diff --git a/library/src/scala/collection/Iterable.scala b/library/src/scala/collection/Iterable.scala index 39f9ba37cc48..1a1044839d33 100644 --- a/library/src/scala/collection/Iterable.scala +++ b/library/src/scala/collection/Iterable.scala @@ -58,7 +58,7 @@ trait Iterable[+A] extends IterableOnce[A] * applied to this $coll. By default the string prefix is the * simple name of the collection class $coll. */ - protected[this] def className: String = stringPrefix + protected def className: String = stringPrefix /** Forwarder to `className` for use in `scala.runtime.ScalaRunTime`. * @@ -70,7 +70,7 @@ trait Iterable[+A] extends IterableOnce[A] private[scala] final def collectionClassName: String = className @deprecatedOverriding("Override className instead", "2.13.0") - protected[this] def stringPrefix: String = "Iterable" + protected def stringPrefix: String = "Iterable" /** Converts this $coll to a string. * @@ -319,7 +319,7 @@ transparent trait IterableOps[+A, +CC[_], +C] extends Any with IterableOnce[A] w * is `O(this.size min that.size)` instead of `O(this.size + that.size)`. * The method should be overridden if computing `size` is cheap and `knownSize` returns `-1`. */ - def sizeCompare(that: Iterable[_]^): Int = { + def sizeCompare(that: Iterable[?]^): Int = { val thatKnownSize = that.knownSize if (thatKnownSize >= 0) this sizeCompare thatKnownSize @@ -846,7 +846,7 @@ transparent trait IterableOps[+A, +CC[_], +C] extends Any with IterableOnce[A] w override def tapEach[U](f: A => U): C^{this, f} = fromSpecific(new View.Map(this, { (a: A) => f(a); a })) // A helper for tails and inits. - private[this] def iterateUntilEmpty(f: Iterable[A]^{this} => Iterable[A]^{this}): Iterator[C^{this}]^{this, f} = { + private def iterateUntilEmpty(f: Iterable[A]^{this} => Iterable[A]^{this}): Iterator[C^{this}]^{this, f} = { // toIterable ties the knot between `this: IterableOnceOps[A, CC, C]` and `this.tail: C` // `this.tail.tail` doesn't compile as `C` is unbounded // `Iterable.from(this)` would eagerly copy non-immutable collections @@ -868,7 +868,7 @@ object IterableOps { * These operations are implemented in terms of * [[scala.collection.IterableOps!.sizeCompare(Int):Int* `sizeCompare(Int)`]] */ - final class SizeCompareOps private[collection](val it: IterableOps[_, AnyConstr, _]) extends AnyVal { + final class SizeCompareOps private[collection](val it: IterableOps[?, AnyConstr, ?]) extends AnyVal { // CC Problem: if we add the logically needed `^`s to the `it` parameter and the // self type, separation checking fails in the compiler-generated equals$extends // method of the value class. There seems to be something wrong how pattern @@ -900,7 +900,7 @@ object IterableOps { */ @SerialVersionUID(3L) class WithFilter[+A, +CC[_]]( - self: IterableOps[A, CC, _]^, + self: IterableOps[A, CC, ?]^, p: A => Boolean ) extends collection.WithFilter[A, CC] with Serializable { @@ -989,8 +989,8 @@ trait EvidenceIterableFactoryDefaults[+A, +CC[x] <: IterableOps[x, CC, CC[x]], E * same as `C`. */ trait SortedSetFactoryDefaults[+A, - +CC[X] <: SortedSet[X] with SortedSetOps[X, CC, CC[X]], - +WithFilterCC[x] <: IterableOps[x, WithFilterCC, WithFilterCC[x]] with Set[x]] extends SortedSetOps[A @uncheckedVariance, CC, CC[A @uncheckedVariance]] { + +CC[X] <: SortedSet[X] & SortedSetOps[X, CC, CC[X]], + +WithFilterCC[x] <: IterableOps[x, WithFilterCC, WithFilterCC[x]] & Set[x]] extends SortedSetOps[A @uncheckedVariance, CC, CC[A @uncheckedVariance]] { self: IterableOps[A, WithFilterCC, CC[A @uncheckedVariance]] => override protected def fromSpecific(coll: IterableOnce[A @uncheckedVariance]^): CC[A @uncheckedVariance] = sortedIterableFactory.from(coll)(using ordering) @@ -1016,7 +1016,7 @@ trait SortedSetFactoryDefaults[+A, */ trait MapFactoryDefaults[K, +V, +CC[x, y] <: IterableOps[(x, y), Iterable, Iterable[(x, y)]], - +WithFilterCC[x] <: IterableOps[x, WithFilterCC, WithFilterCC[x]] with Iterable[x]] extends MapOps[K, V, CC, CC[K, V @uncheckedVariance]] with IterableOps[(K, V), WithFilterCC, CC[K, V @uncheckedVariance]] { + +WithFilterCC[x] <: IterableOps[x, WithFilterCC, WithFilterCC[x]] & Iterable[x]] extends MapOps[K, V, CC, CC[K, V @uncheckedVariance]] with IterableOps[(K, V), WithFilterCC, CC[K, V @uncheckedVariance]] { this: MapFactoryDefaults[K, V, CC, WithFilterCC] => override protected def fromSpecific(coll: IterableOnce[(K, V @uncheckedVariance)]^): CC[K, V @uncheckedVariance]^{coll} = mapFactory.from(coll) override protected def newSpecificBuilder: mutable.Builder[(K, V @uncheckedVariance), CC[K, V @uncheckedVariance]] = mapFactory.newBuilder[K, V] @@ -1043,8 +1043,8 @@ trait MapFactoryDefaults[K, +V, * same as `C`. */ trait SortedMapFactoryDefaults[K, +V, - +CC[x, y] <: Map[x, y] with SortedMapOps[x, y, CC, CC[x, y]] with UnsortedCC[x, y], - +WithFilterCC[x] <: IterableOps[x, WithFilterCC, WithFilterCC[x]] with Iterable[x], + +CC[x, y] <: Map[x, y] & SortedMapOps[x, y, CC, CC[x, y]] & UnsortedCC[x, y], + +WithFilterCC[x] <: IterableOps[x, WithFilterCC, WithFilterCC[x]] & Iterable[x], +UnsortedCC[x, y] <: Map[x, y]] extends SortedMapOps[K, V, CC, CC[K, V @uncheckedVariance]] with MapOps[K, V, UnsortedCC, CC[K, V @uncheckedVariance]] with caps.Pure { self: IterableOps[(K, V), WithFilterCC, CC[K, V @uncheckedVariance]] => diff --git a/library/src/scala/collection/IterableOnce.scala b/library/src/scala/collection/IterableOnce.scala index e70b2aef2dd7..f0fa12e7fa92 100644 --- a/library/src/scala/collection/IterableOnce.scala +++ b/library/src/scala/collection/IterableOnce.scala @@ -77,7 +77,7 @@ trait IterableOnce[+A] extends Any { this: IterableOnce[A]^ => * allow creating parallel streams, whereas bare Steppers can be converted only to sequential * streams. */ - def stepper[S <: Stepper[_]](implicit shape: StepperShape[A, S]): S^{this} = { + def stepper[S <: Stepper[?]](implicit shape: StepperShape[A, S]): S^{this} = { import convert.impl._ val s: Any = shape.shape match { case StepperShape.IntShape => new IntIteratorStepper (iterator.asInstanceOf[Iterator[Int]]) diff --git a/library/src/scala/collection/Iterator.scala b/library/src/scala/collection/Iterator.scala index b3a4d08f6c84..55aaf5469729 100644 --- a/library/src/scala/collection/Iterator.scala +++ b/library/src/scala/collection/Iterator.scala @@ -123,8 +123,8 @@ trait Iterator[+A] extends IterableOnce[A] with IterableOnceOps[A, Iterator, Ite * @note Reuse: $consumesAndProducesIterator */ def buffered: BufferedIterator[A]^{this} = new AbstractIterator[A] with BufferedIterator[A] { - private[this] var hd: A = _ - private[this] var hdDefined: Boolean = false + private var hd: A = compiletime.uninitialized + private var hdDefined: Boolean = false def head: A = { if (!hdDefined) { @@ -162,14 +162,14 @@ trait Iterator[+A] extends IterableOnce[A] with IterableOnceOps[A, Iterator, Ite require(size >= 1 && step >= 1, f"size=$size%d and step=$step%d, but both must be positive") - private[this] var buffer: Array[B] | Null = null // current result - private[this] var prev: Array[B] | Null = null // if sliding, overlap from previous result - private[this] var first = true // if !first, advancing may skip ahead - private[this] var filled = false // whether the buffer is "hot" - private[this] var partial = true // whether to emit partial sequence - private[this] var padding: (() -> B) | Null = null // what to pad short sequences with - private[this] def pad = padding != null // irrespective of partial flag - private[this] def newBuilder = { + private var buffer: Array[B] | Null = null // current result + private var prev: Array[B] | Null = null // if sliding, overlap from previous result + private var first = true // if !first, advancing may skip ahead + private var filled = false // whether the buffer is "hot" + private var partial = true // whether to emit partial sequence + private var padding: (() -> B) | Null = null // what to pad short sequences with + private def pad = padding != null // irrespective of partial flag + private def newBuilder = { val b = ArrayBuilder.make[Any] val k = self.knownSize if (k > 0) b.sizeHint(k min size) // if k < size && !partial, buffer will grow on padding @@ -298,7 +298,7 @@ trait Iterator[+A] extends IterableOnce[A] with IterableOnceOps[A, Iterator, Ite * that the resulting collection has a length of at least `len`. */ def padTo[B >: A](len: Int, elem: B): Iterator[B]^{this} = new AbstractIterator[B] { - private[this] var i = 0 + private var i = 0 override def knownSize: Int = { val thisSize = self.knownSize @@ -389,7 +389,7 @@ trait Iterator[+A] extends IterableOnce[A] with IterableOnceOps[A, Iterator, Ite def scanLeft[B](z: B)(op: (B, A) => B): Iterator[B]^{this, op} = new AbstractIterator[B] { // We use an intermediate iterator that iterates through the first element `z` // and then that will be modified to iterate through the collection - private[this] var current: Iterator[B]^{self, op} = + private var current: Iterator[B]^{self, op} = new AbstractIterator[B] { override def knownSize = { val thisSize = self.knownSize @@ -401,7 +401,7 @@ trait Iterator[+A] extends IterableOnce[A] with IterableOnceOps[A, Iterator, Ite def next(): B = { // Here we change our self-reference to a new iterator that iterates through `self` current = new AbstractIterator[B] { - private[this] var acc = z + private var acc = z def next(): B = { acc = op(acc, self.next()) acc @@ -486,8 +486,8 @@ trait Iterator[+A] extends IterableOnce[A] with IterableOnceOps[A, Iterator, Ite def filterNot(p: A => Boolean): Iterator[A]^{this, p} = filterImpl(p, isFlipped = true) private[collection] def filterImpl(p: A => Boolean, isFlipped: Boolean): Iterator[A]^{this, p} = new AbstractIterator[A] { - private[this] var hd: A = _ - private[this] var hdDefined: Boolean = false + private var hd: A = compiletime.uninitialized + private var hdDefined: Boolean = false def hasNext: Boolean = hdDefined || { if (!self.hasNext) return false @@ -523,13 +523,13 @@ trait Iterator[+A] extends IterableOnce[A] with IterableOnceOps[A, Iterator, Ite def collect[B](pf: PartialFunction[A, B]^): Iterator[B]^{this, pf} = new AbstractIterator[B] with (A => B) { // Manually buffer to avoid extra layer of wrapping with buffered - private[this] var hd: B = _ + private var hd: B = compiletime.uninitialized // Little state machine to keep track of where we are // Seek = 0; Found = 1; Empty = -1 // Not in vals because scalac won't make them static (@inline def only works with -optimize) // BE REALLY CAREFUL TO KEEP COMMENTS AND NUMBERS IN SYNC! - private[this] var status = 0/*Seek*/ + private var status = 0/*Seek*/ def apply(value: A): B = Statics.pfMarker.asInstanceOf[B] @@ -571,9 +571,9 @@ trait Iterator[+A] extends IterableOnce[A] with IterableOnceOps[A, Iterator, Ite */ def distinctBy[B](f: A -> B): Iterator[A]^{this} = new AbstractIterator[A] { - private[this] val traversedValues = mutable.HashSet.empty[B] - private[this] var nextElementDefined: Boolean = false - private[this] var nextElement: A = _ + private val traversedValues = mutable.HashSet.empty[B] + private var nextElementDefined: Boolean = false + private var nextElement: A = compiletime.uninitialized def hasNext: Boolean = nextElementDefined || (self.hasNext && { val a = self.next() @@ -601,9 +601,9 @@ trait Iterator[+A] extends IterableOnce[A] with IterableOnceOps[A, Iterator, Ite } def flatMap[B](f: A => IterableOnce[B]^): Iterator[B]^{this, f} = new AbstractIterator[B] { - private[this] var cur: Iterator[B]^{f} = Iterator.empty + private var cur: Iterator[B]^{f} = Iterator.empty /** Trillium logic boolean: -1 = unknown, 0 = false, 1 = true */ - private[this] var _hasNext: Int = -1 + private var _hasNext: Int = -1 def nextCur(): Unit = { cur = Iterator.empty @@ -645,9 +645,9 @@ trait Iterator[+A] extends IterableOnce[A] with IterableOnceOps[A, Iterator, Ite def take(n: Int): Iterator[A]^{this} = sliceIterator(0, n max 0) def takeWhile(p: A => Boolean): Iterator[A]^{this, p} = new AbstractIterator[A] { - private[this] var hd: A = _ - private[this] var hdDefined: Boolean = false - private[this] var tail: Iterator[A]^{self} = self + private var hd: A = compiletime.uninitialized + private var hdDefined: Boolean = false + private var tail: Iterator[A]^{self} = self def hasNext = hdDefined || tail.hasNext && { hd = tail.next() @@ -662,9 +662,9 @@ trait Iterator[+A] extends IterableOnce[A] with IterableOnceOps[A, Iterator, Ite def dropWhile(p: A => Boolean): Iterator[A]^{this, p} = new AbstractIterator[A] { // Magic value: -1 = hasn't dropped, 0 = found first, 1 = defer to parent iterator - private[this] var status = -1 + private var status = -1 // Local buffering to avoid double-wrap with .buffered - private[this] var fst: A = _ + private var fst: A = compiletime.uninitialized def hasNext: Boolean = if (status == 1) self.hasNext else if (status == 0) true @@ -704,15 +704,15 @@ trait Iterator[+A] extends IterableOnce[A] with IterableOnceOps[A, Iterator, Ite * handling of structural calls. It's not what's intended here. */ final class Leading extends AbstractIterator[A] { - private[this] var lookahead: mutable.Queue[A] | Null = null - private[this] var hd: A = _ + private var lookahead: mutable.Queue[A] | Null = null + private var hd: A = compiletime.uninitialized /* Status is kept with magic numbers * 1 means next element is in hd and we're still reading into this iterator * 0 means we're still reading but haven't found a next element * -1 means we are done reading into the iterator, so we must rely on lookahead * -2 means we are done but have saved hd for the other iterator to use as its first element */ - private[this] var status = 0 + private var status = 0 private def store(a: A): Unit = { if (lookahead == null) lookahead = new mutable.Queue[A] lookahead.nn += a @@ -759,7 +759,7 @@ trait Iterator[+A] extends IterableOnce[A] with IterableOnceOps[A, Iterator, Ite val leading = new Leading val trailing = new AbstractIterator[A] { - private[this] var myLeading = leading + private var myLeading = leading /* Status flag meanings: * -1 not yet accessed * 0 single element waiting in leading @@ -767,7 +767,7 @@ trait Iterator[+A] extends IterableOnce[A] with IterableOnceOps[A, Iterator, Ite * 2 self.hasNext already * 3 exhausted */ - private[this] var status = -1 + private var status = -1 def hasNext = status match { case 3 => false case 2 => true @@ -924,15 +924,15 @@ trait Iterator[+A] extends IterableOnce[A] with IterableOnceOps[A, Iterator, Ite // freh cap. Maybe we can invent another annotation that is checked and that // shows that the `^` is just used as an upper bound for concete non-fresh // capabilities. - @untrackedCaptures private[this] var origElems: Iterator[B]^ = self + @untrackedCaptures private var origElems: Iterator[B]^ = self // > 0 => that many more elems from `origElems` before switching to `patchElems` // 0 => need to drop elems from `origElems` and start using `patchElems` // -1 => have dropped elems from `origElems`, will be using `patchElems` until it's empty // and then using what's left of `origElems` after the drop - private[this] var state = if (from > 0) from else 0 + private var state = if (from > 0) from else 0 // checks state and handles 0 => -1 - @inline private[this] def switchToPatchIfNeeded(): Unit = + @inline private def switchToPatchIfNeeded(): Unit = if (state == 0) { origElems = origElems drop replaced state = -1 @@ -986,7 +986,7 @@ trait Iterator[+A] extends IterableOnce[A] with IterableOnceOps[A, Iterator, Ite @SerialVersionUID(3L) object Iterator extends IterableFactory[Iterator] { - private[this] val _empty: Iterator[Nothing] = new AbstractIterator[Nothing] { + private val _empty: Iterator[Nothing] = new AbstractIterator[Nothing] { def hasNext = false def next() = throw new NoSuchElementException("next on empty iterator") override def knownSize: Int = 0 @@ -1005,7 +1005,7 @@ object Iterator extends IterableFactory[Iterator] { @`inline` final def empty[T]: Iterator[T] = _empty def single[A](a: A): Iterator[A] = new AbstractIterator[A] { - private[this] var consumed: Boolean = false + private var consumed: Boolean = false def hasNext = !consumed def next() = if (consumed) empty.next() else { consumed = true; a } override protected def sliceIterator(from: Int, until: Int) = @@ -1031,7 +1031,7 @@ object Iterator extends IterableFactory[Iterator] { * @return An iterator that produces the results of `n` evaluations of `elem`. */ override def fill[A](len: Int)(elem: => A): Iterator[A]^{elem} = new AbstractIterator[A] { - private[this] var i = 0 + private var i = 0 override def knownSize: Int = (len - i) max 0 def hasNext: Boolean = i < len def next(): A = @@ -1046,7 +1046,7 @@ object Iterator extends IterableFactory[Iterator] { * @return An iterator that produces the values `f(0), ..., f(n -1)`. */ override def tabulate[A](end: Int)(f: Int => A): Iterator[A]^{f} = new AbstractIterator[A] { - private[this] var i = 0 + private var i = 0 override def knownSize: Int = (end - i) max 0 def hasNext: Boolean = i < end def next(): A = @@ -1068,7 +1068,7 @@ object Iterator extends IterableFactory[Iterator] { * @return the iterator producing the infinite sequence of values `start, start + 1 * step, start + 2 * step, ...` */ def from(start: Int, step: Int): Iterator[Int] = new AbstractIterator[Int] { - private[this] var i = start + private var i = start def hasNext: Boolean = true def next(): Int = { val result = i; i += step; result } } @@ -1090,8 +1090,8 @@ object Iterator extends IterableFactory[Iterator] { */ def range(start: Int, end: Int, step: Int): Iterator[Int] = new AbstractIterator[Int] { if (step == 0) throw new IllegalArgumentException("zero step") - private[this] var i = start - private[this] var hasOverflowed = false + private var i = start + private var hasOverflowed = false override def knownSize: Int = { val size = math.ceil((end.toLong - i.toLong) / step.toDouble) if (size < 0) 0 @@ -1119,8 +1119,8 @@ object Iterator extends IterableFactory[Iterator] { * @return the iterator producing the infinite sequence of values `start, f(start), f(f(start)), ...` */ def iterate[T](start: T)(f: T => T): Iterator[T]^{f} = new AbstractIterator[T] { - private[this] var first = true - private[this] var acc = start + private var first = true + private var acc = start def hasNext: Boolean = true def next(): T = { if (first) first = false @@ -1175,7 +1175,7 @@ object Iterator extends IterableFactory[Iterator] { else { // If we advanced the current iterator to a ConcatIterator, merge it into this one @tailrec def merge(): Unit = - if (current.isInstanceOf[ConcatIterator[_]]) { + if (current.isInstanceOf[ConcatIterator[?]]) { val c = current.asInstanceOf[ConcatIterator[A]^{from}] current = c.current currentHasNextChecked = c.currentHasNextChecked @@ -1231,7 +1231,7 @@ object Iterator extends IterableFactory[Iterator] { } } - private[this] final class ConcatIteratorCell[A](head: => IterableOnce[A]^, var tail: (ConcatIteratorCell[A]^) | Null) { + private final class ConcatIteratorCell[A](head: => IterableOnce[A]^, var tail: (ConcatIteratorCell[A]^) | Null) { def headIterator: Iterator[A]^{this} = head.iterator } @@ -1239,8 +1239,8 @@ object Iterator extends IterableFactory[Iterator] { * Lazily skip to start on first evaluation. Avoids daisy-chained iterators due to slicing. */ private[scala] final class SliceIterator[A](val underlying: Iterator[A]^, start: Int, limit: Int) extends AbstractIterator[A] { - private[this] var remaining = limit - private[this] var dropping = start + private var remaining = limit + private var dropping = start @inline private def unbounded = remaining < 0 private def skip(): Unit = while (dropping > 0) { @@ -1298,8 +1298,8 @@ object Iterator extends IterableFactory[Iterator] { * type `A` and update an internal state of type `S`. */ private final class UnfoldIterator[A, S](init: S)(f: S => Option[(A, S)]) extends AbstractIterator[A] { - private[this] var state: S = init - private[this] var nextResult: Option[(A, S)] | Null = null + private var state: S = init + private var nextResult: Option[(A, S)] | Null = null override def hasNext: Boolean = { if (nextResult eq null) { diff --git a/library/src/scala/collection/LazyZipOps.scala b/library/src/scala/collection/LazyZipOps.scala index 7e2e6a5ed66f..899227167fee 100644 --- a/library/src/scala/collection/LazyZipOps.scala +++ b/library/src/scala/collection/LazyZipOps.scala @@ -38,8 +38,8 @@ final class LazyZip2[+El1, +El2, C1] private[collection](src: C1, coll1: Iterabl def map[B, C](f: (El1, El2) => B)(implicit bf: BuildFrom[C1, B, C]): C^{this, f} = { bf.fromSpecific(src)(new AbstractView[B] { def iterator: AbstractIterator[B]^{this, f} = new AbstractIterator[B] { - private[this] val elems1 = coll1.iterator - private[this] val elems2 = coll2.iterator + private val elems1 = coll1.iterator + private val elems2 = coll2.iterator def hasNext = elems1.hasNext && elems2.hasNext def next() = f(elems1.next(), elems2.next()) } @@ -51,9 +51,9 @@ final class LazyZip2[+El1, +El2, C1] private[collection](src: C1, coll1: Iterabl def flatMap[B, C](f: (El1, El2) => Iterable[B]^)(implicit bf: BuildFrom[C1, B, C]): C^{this, f} = { bf.fromSpecific(src)(new AbstractView[B] { def iterator: AbstractIterator[B]^{this, f} = new AbstractIterator[B] { - private[this] val elems1 = coll1.iterator - private[this] val elems2 = coll2.iterator - private[this] var _current: Iterator[B]^{this, f} = Iterator.empty + private val elems1 = coll1.iterator + private val elems2 = coll2.iterator + private var _current: Iterator[B]^{this, f} = Iterator.empty private def current = { while (!_current.hasNext && elems1.hasNext && elems2.hasNext) _current = f(elems1.next(), elems2.next()).iterator @@ -70,9 +70,9 @@ final class LazyZip2[+El1, +El2, C1] private[collection](src: C1, coll1: Iterabl def filter[C](p: (El1, El2) => Boolean)(implicit bf: BuildFrom[C1, (El1, El2), C]): C^{this, p} = { bf.fromSpecific(src)(new AbstractView[(El1, El2)] { def iterator: AbstractIterator[(El1, El2)]^{this, p} = new AbstractIterator[(El1, El2)] { - private[this] val elems1 = coll1.iterator - private[this] val elems2 = coll2.iterator - private[this] var _current: (El1, El2) | Null = _ + private val elems1 = coll1.iterator + private val elems2 = coll2.iterator + private var _current: (El1, El2) | Null = compiletime.uninitialized private def current = { while ((_current eq null) && elems1.hasNext && elems2.hasNext) { val e1 = elems1.next() @@ -116,8 +116,8 @@ final class LazyZip2[+El1, +El2, C1] private[collection](src: C1, coll1: Iterabl private def toIterable: View[(El1, El2)]^{this} = new AbstractView[(El1, El2)] { def iterator: AbstractIterator[(El1, El2)]^{this} = new AbstractIterator[(El1, El2)] { - private[this] val elems1 = coll1.iterator - private[this] val elems2 = coll2.iterator + private val elems1 = coll1.iterator + private val elems2 = coll2.iterator def hasNext = elems1.hasNext && elems2.hasNext def next() = (elems1.next(), elems2.next()) } @@ -137,7 +137,7 @@ final class LazyZip2[+El1, +El2, C1] private[collection](src: C1, coll1: Iterabl } object LazyZip2 { - implicit def lazyZip2ToIterable[El1, El2](zipped2: LazyZip2[El1, El2, _]^): View[(El1, El2)]^{zipped2} = zipped2.toIterable + implicit def lazyZip2ToIterable[El1, El2](zipped2: LazyZip2[El1, El2, ?]^): View[(El1, El2)]^{zipped2} = zipped2.toIterable } @@ -166,9 +166,9 @@ final class LazyZip3[+El1, +El2, +El3, C1] private[collection](src: C1, def map[B, C](f: (El1, El2, El3) => B)(implicit bf: BuildFrom[C1, B, C]): C^{this, f} = { bf.fromSpecific(src)(new AbstractView[B] { def iterator: AbstractIterator[B]^{this, f} = new AbstractIterator[B] { - private[this] val elems1 = coll1.iterator - private[this] val elems2 = coll2.iterator - private[this] val elems3 = coll3.iterator + private val elems1 = coll1.iterator + private val elems2 = coll2.iterator + private val elems3 = coll3.iterator def hasNext = elems1.hasNext && elems2.hasNext && elems3.hasNext def next() = f(elems1.next(), elems2.next(), elems3.next()) } @@ -180,10 +180,10 @@ final class LazyZip3[+El1, +El2, +El3, C1] private[collection](src: C1, def flatMap[B, C](f: (El1, El2, El3) => Iterable[B]^)(implicit bf: BuildFrom[C1, B, C]): C^{this, f} = { bf.fromSpecific(src)(new AbstractView[B] { def iterator: AbstractIterator[B]^{this, f} = new AbstractIterator[B] { - private[this] val elems1 = coll1.iterator - private[this] val elems2 = coll2.iterator - private[this] val elems3 = coll3.iterator - private[this] var _current: Iterator[B]^{this, f} = Iterator.empty + private val elems1 = coll1.iterator + private val elems2 = coll2.iterator + private val elems3 = coll3.iterator + private var _current: Iterator[B]^{this, f} = Iterator.empty private def current = { while (!_current.hasNext && elems1.hasNext && elems2.hasNext && elems3.hasNext) _current = f(elems1.next(), elems2.next(), elems3.next()).iterator @@ -200,10 +200,10 @@ final class LazyZip3[+El1, +El2, +El3, C1] private[collection](src: C1, def filter[C](p: (El1, El2, El3) => Boolean)(implicit bf: BuildFrom[C1, (El1, El2, El3), C]): C^{this, p} = { bf.fromSpecific(src)(new AbstractView[(El1, El2, El3)] { def iterator: AbstractIterator[(El1, El2, El3)]^{this, p} = new AbstractIterator[(El1, El2, El3)] { - private[this] val elems1 = coll1.iterator - private[this] val elems2 = coll2.iterator - private[this] val elems3 = coll3.iterator - private[this] var _current: (El1, El2, El3) | Null = _ + private val elems1 = coll1.iterator + private val elems2 = coll2.iterator + private val elems3 = coll3.iterator + private var _current: (El1, El2, El3) | Null = compiletime.uninitialized private def current = { while ((_current eq null) && elems1.hasNext && elems2.hasNext && elems3.hasNext) { val e1 = elems1.next() @@ -252,9 +252,9 @@ final class LazyZip3[+El1, +El2, +El3, C1] private[collection](src: C1, private def toIterable: View[(El1, El2, El3)]^{this} = new AbstractView[(El1, El2, El3)] { def iterator: AbstractIterator[(El1, El2, El3)]^{this} = new AbstractIterator[(El1, El2, El3)] { - private[this] val elems1 = coll1.iterator - private[this] val elems2 = coll2.iterator - private[this] val elems3 = coll3.iterator + private val elems1 = coll1.iterator + private val elems2 = coll2.iterator + private val elems3 = coll3.iterator def hasNext = elems1.hasNext && elems2.hasNext && elems3.hasNext def next() = (elems1.next(), elems2.next(), elems3.next()) } @@ -277,7 +277,7 @@ final class LazyZip3[+El1, +El2, +El3, C1] private[collection](src: C1, } object LazyZip3 { - implicit def lazyZip3ToIterable[El1, El2, El3](zipped3: LazyZip3[El1, El2, El3, _]^): View[(El1, El2, El3)]^{zipped3} = zipped3.toIterable + implicit def lazyZip3ToIterable[El1, El2, El3](zipped3: LazyZip3[El1, El2, El3, ?]^): View[(El1, El2, El3)]^{zipped3} = zipped3.toIterable } @@ -298,10 +298,10 @@ final class LazyZip4[+El1, +El2, +El3, +El4, C1] private[collection](src: C1, def map[B, C](f: (El1, El2, El3, El4) => B)(implicit bf: BuildFrom[C1, B, C]): C^{this, f} = { bf.fromSpecific(src)(new AbstractView[B] { def iterator: AbstractIterator[B]^{this, f} = new AbstractIterator[B] { - private[this] val elems1 = coll1.iterator - private[this] val elems2 = coll2.iterator - private[this] val elems3 = coll3.iterator - private[this] val elems4 = coll4.iterator + private val elems1 = coll1.iterator + private val elems2 = coll2.iterator + private val elems3 = coll3.iterator + private val elems4 = coll4.iterator def hasNext = elems1.hasNext && elems2.hasNext && elems3.hasNext && elems4.hasNext def next() = f(elems1.next(), elems2.next(), elems3.next(), elems4.next()) } @@ -313,11 +313,11 @@ final class LazyZip4[+El1, +El2, +El3, +El4, C1] private[collection](src: C1, def flatMap[B, C](f: (El1, El2, El3, El4) => Iterable[B]^)(implicit bf: BuildFrom[C1, B, C]): C^{this, f} = { bf.fromSpecific(src)(new AbstractView[B] { def iterator: AbstractIterator[B]^{this, f} = new AbstractIterator[B] { - private[this] val elems1 = coll1.iterator - private[this] val elems2 = coll2.iterator - private[this] val elems3 = coll3.iterator - private[this] val elems4 = coll4.iterator - private[this] var _current: Iterator[B]^{this, f} = Iterator.empty + private val elems1 = coll1.iterator + private val elems2 = coll2.iterator + private val elems3 = coll3.iterator + private val elems4 = coll4.iterator + private var _current: Iterator[B]^{this, f} = Iterator.empty private def current = { while (!_current.hasNext && elems1.hasNext && elems2.hasNext && elems3.hasNext && elems4.hasNext) _current = f(elems1.next(), elems2.next(), elems3.next(), elems4.next()).iterator @@ -334,11 +334,11 @@ final class LazyZip4[+El1, +El2, +El3, +El4, C1] private[collection](src: C1, def filter[C](p: (El1, El2, El3, El4) => Boolean)(implicit bf: BuildFrom[C1, (El1, El2, El3, El4), C]): C^{this, p} = { bf.fromSpecific(src)(new AbstractView[(El1, El2, El3, El4)] { def iterator: AbstractIterator[(El1, El2, El3, El4)]^{this, p} = new AbstractIterator[(El1, El2, El3, El4)] { - private[this] val elems1 = coll1.iterator - private[this] val elems2 = coll2.iterator - private[this] val elems3 = coll3.iterator - private[this] val elems4 = coll4.iterator - private[this] var _current: (El1, El2, El3, El4) | Null = _ + private val elems1 = coll1.iterator + private val elems2 = coll2.iterator + private val elems3 = coll3.iterator + private val elems4 = coll4.iterator + private var _current: (El1, El2, El3, El4) | Null = compiletime.uninitialized private def current = { while ((_current eq null) && elems1.hasNext && elems2.hasNext && elems3.hasNext && elems4.hasNext) { val e1 = elems1.next() @@ -390,10 +390,10 @@ final class LazyZip4[+El1, +El2, +El3, +El4, C1] private[collection](src: C1, private def toIterable: View[(El1, El2, El3, El4)]^{this} = new AbstractView[(El1, El2, El3, El4)] { def iterator: AbstractIterator[(El1, El2, El3, El4)]^{this} = new AbstractIterator[(El1, El2, El3, El4)] { - private[this] val elems1 = coll1.iterator - private[this] val elems2 = coll2.iterator - private[this] val elems3 = coll3.iterator - private[this] val elems4 = coll4.iterator + private val elems1 = coll1.iterator + private val elems2 = coll2.iterator + private val elems3 = coll3.iterator + private val elems4 = coll4.iterator def hasNext = elems1.hasNext && elems2.hasNext && elems3.hasNext && elems4.hasNext def next() = (elems1.next(), elems2.next(), elems3.next(), elems4.next()) } @@ -419,6 +419,6 @@ final class LazyZip4[+El1, +El2, +El3, +El4, C1] private[collection](src: C1, } object LazyZip4 { - implicit def lazyZip4ToIterable[El1, El2, El3, El4](zipped4: LazyZip4[El1, El2, El3, El4, _]^): View[(El1, El2, El3, El4)]^{zipped4} = + implicit def lazyZip4ToIterable[El1, El2, El3, El4](zipped4: LazyZip4[El1, El2, El3, El4, ?]^): View[(El1, El2, El3, El4)]^{zipped4} = zipped4.toIterable } diff --git a/library/src/scala/collection/LinearSeq.scala b/library/src/scala/collection/LinearSeq.scala index 4c79575a22a8..97a1c09d53af 100644 --- a/library/src/scala/collection/LinearSeq.scala +++ b/library/src/scala/collection/LinearSeq.scala @@ -26,7 +26,7 @@ trait LinearSeq[+A] extends Seq[A] with LinearSeqOps[A, LinearSeq, LinearSeq[A]] with IterableFactoryDefaults[A, LinearSeq] { @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix: String = "LinearSeq" + override protected def stringPrefix: String = "LinearSeq" override def iterableFactory: SeqFactory[LinearSeq] = LinearSeq } @@ -35,7 +35,7 @@ trait LinearSeq[+A] extends Seq[A] object LinearSeq extends SeqFactory.Delegate[LinearSeq](immutable.LinearSeq) /** Base trait for linear Seq operations */ -transparent trait LinearSeqOps[+A, +CC[X] <: LinearSeq[X], +C <: LinearSeq[A] with LinearSeqOps[A, CC, C]] extends Any with SeqOps[A, CC, C] with caps.Pure { self => +transparent trait LinearSeqOps[+A, +CC[X] <: LinearSeq[X], +C <: LinearSeq[A] & LinearSeqOps[A, CC, C]] extends Any with SeqOps[A, CC, C] with caps.Pure { self => /** @inheritdoc * @@ -99,7 +99,7 @@ transparent trait LinearSeqOps[+A, +CC[X] <: LinearSeq[X], +C <: LinearSeq[A] wi else loop(0, coll) } - override def lengthCompare(that: Iterable[_]^): Int = { + override def lengthCompare(that: Iterable[?]^): Int = { val thatKnownSize = that.knownSize if (thatKnownSize >= 0) this lengthCompare thatKnownSize @@ -262,10 +262,10 @@ transparent trait LinearSeqOps[+A, +CC[X] <: LinearSeq[X], +C <: LinearSeq[A] wi } } -transparent trait StrictOptimizedLinearSeqOps[+A, +CC[X] <: LinearSeq[X], +C <: LinearSeq[A] with StrictOptimizedLinearSeqOps[A, CC, C]] extends Any with LinearSeqOps[A, CC, C] with StrictOptimizedSeqOps[A, CC, C] { self => +transparent trait StrictOptimizedLinearSeqOps[+A, +CC[X] <: LinearSeq[X], +C <: LinearSeq[A] & StrictOptimizedLinearSeqOps[A, CC, C]] extends Any with LinearSeqOps[A, CC, C] with StrictOptimizedSeqOps[A, CC, C] { self => // A more efficient iterator implementation than the default LinearSeqIterator override def iterator: Iterator[A] = new AbstractIterator[A] { - private[this] var current = StrictOptimizedLinearSeqOps.this + private var current = StrictOptimizedLinearSeqOps.this def hasNext = !current.isEmpty def next() = { val r = current.head; current = current.tail; r } } @@ -291,9 +291,9 @@ transparent trait StrictOptimizedLinearSeqOps[+A, +CC[X] <: LinearSeq[X], +C <: */ private[collection] final class LinearSeqIterator[A](coll: LinearSeqOps[A, LinearSeq, LinearSeq[A]]) extends AbstractIterator[A] { // A call-by-need cell - private[this] final class LazyCell(st: => LinearSeqOps[A, LinearSeq, LinearSeq[A]]) { lazy val v = st } + private final class LazyCell(st: => LinearSeqOps[A, LinearSeq, LinearSeq[A]]) { lazy val v = st } - private[this] var these: LazyCell = { + private var these: LazyCell = { // Reassign reference to avoid creating a private class field and holding a reference to the head. // LazyCell would otherwise close over `coll`. val initialHead = coll diff --git a/library/src/scala/collection/Map.scala b/library/src/scala/collection/Map.scala index 998b24108ffe..cca10fa3581b 100644 --- a/library/src/scala/collection/Map.scala +++ b/library/src/scala/collection/Map.scala @@ -84,7 +84,7 @@ trait Map[K, +V] def - (key1: K, key2: K, keys: K*): Map[K, V] @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix: String = "Map" + override protected def stringPrefix: String = "Map" override def toString(): String = super[Iterable].toString() // Because `Function1` overrides `toString` too } @@ -102,14 +102,14 @@ trait Map[K, +V] */ // Note: the upper bound constraint on CC is useful only to // erase CC to IterableOps instead of Object -transparent trait MapOps[K, +V, +CC[_, _] <: IterableOps[_, AnyConstr, _], +C] +transparent trait MapOps[K, +V, +CC[_, _] <: IterableOps[?, AnyConstr, ?], +C] extends IterableOps[(K, V), Iterable, C] with PartialFunction[K, V] { self: MapOps[K, V, CC, C]^ => override def view: MapView[K, V]^{this} = new MapView.Id(this) /** Returns a [[Stepper]] for the keys of this map. See method [[stepper]]. */ - def keyStepper[S <: Stepper[_]](implicit shape: StepperShape[K, S]): S = { + def keyStepper[S <: Stepper[?]](implicit shape: StepperShape[K, S]): S = { import convert.impl._ val s = shape.shape match { case StepperShape.IntShape => new IntIteratorStepper (keysIterator.asInstanceOf[Iterator[Int]]) @@ -121,7 +121,7 @@ transparent trait MapOps[K, +V, +CC[_, _] <: IterableOps[_, AnyConstr, _], +C] } /** Returns a [[Stepper]] for the values of this map. See method [[stepper]]. */ - def valueStepper[S <: Stepper[_]](implicit shape: StepperShape[V, S]): S = { + def valueStepper[S <: Stepper[?]](implicit shape: StepperShape[V, S]): S = { import convert.impl._ val s = shape.shape match { case StepperShape.IntShape => new IntIteratorStepper (valuesIterator.asInstanceOf[Iterator[Int]]) @@ -407,8 +407,8 @@ object MapOps { * @define coll map collection */ @SerialVersionUID(3L) - class WithFilter[K, +V, +IterableCC[_], +CC[_, _] <: IterableOps[_, AnyConstr, _]]( - self: (MapOps[K, V, CC, _] with IterableOps[(K, V), IterableCC, _])^, + class WithFilter[K, +V, +IterableCC[_], +CC[_, _] <: IterableOps[?, AnyConstr, ?]]( + self: (MapOps[K, V, CC, ?] & IterableOps[(K, V), IterableCC, ?])^, p: ((K, V)) => Boolean ) extends IterableOps.WithFilter[(K, V), IterableCC](self, p) with Serializable { @@ -426,7 +426,7 @@ object MapOps { /** The implementation class of the set returned by `keySet`, for pure maps. */ - private class LazyKeySet[K, +V, +CC[_, _] <: IterableOps[_, AnyConstr, _], +C](mp: MapOps[K, V, CC, C]) extends AbstractSet[K] with DefaultSerializable { + private class LazyKeySet[K, +V, +CC[_, _] <: IterableOps[?, AnyConstr, ?], +C](mp: MapOps[K, V, CC, C]) extends AbstractSet[K] with DefaultSerializable { def iterator: Iterator[K] = mp.keysIterator def diff(that: Set[K]): Set[K] = LazyKeySet.this.fromSpecific(this.view.filterNot(that)) def contains(key: K): Boolean = mp.contains(key) diff --git a/library/src/scala/collection/MapView.scala b/library/src/scala/collection/MapView.scala index 5ede734455b3..4b021acd5c05 100644 --- a/library/src/scala/collection/MapView.scala +++ b/library/src/scala/collection/MapView.scala @@ -71,15 +71,15 @@ trait MapView[K, +V] override def toString: String = super[View].toString @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix: String = "MapView" + override protected def stringPrefix: String = "MapView" } object MapView extends MapViewFactory { /** An `IterableOps` whose collection type and collection type constructor are unknown */ - type SomeIterableConstr[X, Y] = IterableOps[_, AnyConstr, _] + type SomeIterableConstr[X, Y] = IterableOps[?, AnyConstr, ?] /** A `MapOps` whose collection type and collection type constructor are (mostly) unknown */ - type SomeMapOps[K, +V] = MapOps[K, V, SomeIterableConstr, _] + type SomeMapOps[K, +V] = MapOps[K, V, SomeIterableConstr, ?] @SerialVersionUID(3L) private val EmptyMapView: MapView[Any, Nothing] = new AbstractMapView[Any, Nothing] { @@ -104,7 +104,7 @@ object MapView extends MapViewFactory { // Ideally this is public, but bincompat @SerialVersionUID(3L) - private class Keys[K](underlying: SomeMapOps[K, _]^) extends AbstractView[K] { + private class Keys[K](underlying: SomeMapOps[K, ?]^) extends AbstractView[K] { def iterator: Iterator[K]^{this} = underlying.keysIterator override def knownSize: Int = underlying.knownSize override def isEmpty: Boolean = underlying.isEmpty @@ -112,7 +112,7 @@ object MapView extends MapViewFactory { // Ideally this is public, but bincompat @SerialVersionUID(3L) - private class Values[+V](underlying: SomeMapOps[_, V]^) extends AbstractView[V] { + private class Values[+V](underlying: SomeMapOps[?, V]^) extends AbstractView[V] { def iterator: Iterator[V]^{this} = underlying.valuesIterator override def knownSize: Int = underlying.knownSize override def isEmpty: Boolean = underlying.isEmpty diff --git a/library/src/scala/collection/Searching.scala b/library/src/scala/collection/Searching.scala index cd5842f81057..a65d1ff69ba8 100644 --- a/library/src/scala/collection/Searching.scala +++ b/library/src/scala/collection/Searching.scala @@ -52,7 +52,7 @@ object Searching { case class InsertionPoint(insertionPoint: Int) extends SearchResult @deprecated("Search methods are defined directly on SeqOps and do not require scala.collection.Searching any more", "2.13.0") - class SearchImpl[Repr, A](private val coll: SeqOps[A, AnyConstr, _]) extends AnyVal + class SearchImpl[Repr, A](private val coll: SeqOps[A, AnyConstr, ?]) extends AnyVal @deprecated("Search methods are defined directly on SeqOps and do not require scala.collection.Searching any more", "2.13.0") implicit def search[Repr, A](coll: Repr)(implicit fr: IsSeq[Repr]): SearchImpl[Repr, fr.A] = diff --git a/library/src/scala/collection/Seq.scala b/library/src/scala/collection/Seq.scala index 46e488ba4662..839722a0dfbc 100644 --- a/library/src/scala/collection/Seq.scala +++ b/library/src/scala/collection/Seq.scala @@ -47,7 +47,7 @@ trait Seq[+A] override def toString(): String = super[Iterable].toString() @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix: String = "Seq" + override protected def stringPrefix: String = "Seq" } /** @@ -416,7 +416,7 @@ transparent trait SeqOps[+A, +CC[_], +C] extends Any @deprecatedOverriding("Override lastIndexWhere(p, end) instead - lastIndexWhere(p) calls lastIndexWhere(p, Int.MaxValue)", "2.13.0") def lastIndexWhere(p: A => Boolean): Int = lastIndexWhere(p, Int.MaxValue) - @inline private[this] def toGenericSeq: scala.collection.Seq[A] = this match { + @inline private def toGenericSeq: scala.collection.Seq[A] = this match { case s: scala.collection.Seq[A] => s case _ => toSeq } @@ -590,8 +590,8 @@ transparent trait SeqOps[+A, +CC[_], +C] extends Any else new CombinationsItr(n) private class PermutationsItr extends AbstractIterator[C] { - private[this] val (elms, idxs) = init() - private[this] var _hasNext = true + private val (elms, idxs) = init() + private var _hasNext = true def hasNext = _hasNext @throws[NoSuchElementException] @@ -630,7 +630,7 @@ transparent trait SeqOps[+A, +CC[_], +C] extends Any elms(j) = tmpE } - private[this] def init() = { + private def init() = { val m = mutable.HashMap[A, Int]() val (es, is) = (self.toGenericSeq map (e => (e, m.getOrElseUpdate(e, m.size))) sortBy (_._2)).unzip @@ -642,9 +642,9 @@ transparent trait SeqOps[+A, +CC[_], +C] extends Any // generating all nums such that: // (1) nums(0) + .. + nums(length-1) = n // (2) 0 <= nums(i) <= cnts(i), where 0 <= i <= cnts.length-1 - private[this] val (elms, cnts, nums) = init() - private[this] val offs = cnts.scanLeft(0)(_ + _) - private[this] var _hasNext = true + private val (elms, cnts, nums) = init() + private val offs = cnts.scanLeft(0)(_ + _) + private var _hasNext = true def hasNext = _hasNext def next(): C = { @@ -757,7 +757,7 @@ transparent trait SeqOps[+A, +CC[_], +C] extends Any * List("Bobby", "Bob", "John", "Steve", "Tom") * }}} */ - def sortWith(lt: (A, A) => Boolean): C^{this} = sorted(Ordering.fromLessThan(lt)) + def sortWith(lt: (A, A) => Boolean): C^{this} = sorted(using Ordering.fromLessThan(lt)) /** Sorts this $coll according to the Ordering which results from transforming * an implicitly given Ordering with a transformation function. @@ -784,7 +784,7 @@ transparent trait SeqOps[+A, +CC[_], +C] extends Any * res0: Array[String] = Array(The, dog, fox, the, lazy, over, brown, quick, jumped) * }}} */ - def sortBy[B](f: A => B)(implicit ord: Ordering[B]): C^{this} = sorted(ord on f) + def sortBy[B](f: A => B)(implicit ord: Ordering[B]): C^{this} = sorted(using ord.on(f)) /** Produces the range of all indices of this sequence. * $willForceEvaluation @@ -812,7 +812,7 @@ transparent trait SeqOps[+A, +CC[_], +C] extends Any */ def lengthCompare(len: Int): Int = super.sizeCompare(len) - override final def sizeCompare(that: Iterable[_]^): Int = lengthCompare(that) + override final def sizeCompare(that: Iterable[?]^): Int = lengthCompare(that) /** Compares the length of this $coll to the size of another `Iterable`. * @@ -827,7 +827,7 @@ transparent trait SeqOps[+A, +CC[_], +C] extends Any * is `O(this.length min that.size)` instead of `O(this.length + that.size)`. * The method should be overridden if computing `size` is cheap and `knownSize` returns `-1`. */ - def lengthCompare(that: Iterable[_]^): Int = super.sizeCompare(that) + def lengthCompare(that: Iterable[?]^): Int = super.sizeCompare(that) /** Returns a value class containing operations for comparing the length of this $coll to a test value. * @@ -995,7 +995,7 @@ transparent trait SeqOps[+A, +CC[_], +C] extends Any * the element is not in the sequence. */ def search[B >: A](elem: B)(implicit ord: Ordering[B]): SearchResult = - linearSearch(view, elem, 0)(ord) + linearSearch(view, elem, 0)(using ord) /** Searches within an interval in this sorted sequence for a specific element. If this * sequence is an `IndexedSeq`, a binary search is used. Otherwise, a linear search @@ -1021,9 +1021,9 @@ transparent trait SeqOps[+A, +CC[_], +C] extends Any * is returned */ def search[B >: A](elem: B, from: Int, to: Int) (implicit ord: Ordering[B]): SearchResult = - linearSearch(view.slice(from, to), elem, math.max(0, from))(ord) + linearSearch(view.slice(from, to), elem, math.max(0, from))(using ord) - private[this] def linearSearch[B >: A](c: View[A]^, elem: B, offset: Int) + private def linearSearch[B >: A](c: View[A]^, elem: B, offset: Int) (implicit ord: Ordering[B]): SearchResult = { var idx = offset val it = c.iterator @@ -1152,9 +1152,9 @@ object SeqOps { // W is probably bad at indexing. Pack in array (in correct orientation) // Would be marginally faster to special-case each direction new AbstractIndexedSeqView[B] { - private[this] val Warr = new Array[AnyRef](n1-n0) - private[this] val delta = if (forward) 1 else -1 - private[this] val done = if (forward) n1-n0 else -1 + private val Warr = new Array[AnyRef](n1-n0) + private val delta = if (forward) 1 else -1 + private val done = if (forward) n1-n0 else -1 val wit = W.iterator.drop(n0) var i = if (forward) 0 else (n1-n0-1) while (i != done) { diff --git a/library/src/scala/collection/SeqMap.scala b/library/src/scala/collection/SeqMap.scala index eaf7bcea6852..034794a98474 100644 --- a/library/src/scala/collection/SeqMap.scala +++ b/library/src/scala/collection/SeqMap.scala @@ -34,7 +34,7 @@ trait SeqMap[K, +V] extends Map[K, V] with MapOps[K, V, SeqMap, SeqMap[K, V]] with MapFactoryDefaults[K, V, SeqMap, Iterable] { @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix: String = "SeqMap" + override protected def stringPrefix: String = "SeqMap" override def mapFactory: MapFactory[SeqMap] = SeqMap } diff --git a/library/src/scala/collection/SeqView.scala b/library/src/scala/collection/SeqView.scala index 21b771d4e13c..63ffd17fc109 100644 --- a/library/src/scala/collection/SeqView.scala +++ b/library/src/scala/collection/SeqView.scala @@ -41,13 +41,13 @@ trait SeqView[+A] extends SeqOps[A, View, View[A]] with View[A] { override def sorted[B >: A](implicit ord: Ordering[B]): SeqView[A]^{this} = new SeqView.Sorted(this, ord) @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix: String = "SeqView" + override protected def stringPrefix: String = "SeqView" } object SeqView { /** A `SeqOps` whose collection type and collection type constructor are unknown */ - private type SomeSeqOps[+A] = SeqOps[A, AnyConstr, _] + private type SomeSeqOps[+A] = SeqOps[A, AnyConstr, ?] /** A view that doesn’t apply any transformation to an underlying sequence */ @SerialVersionUID(3L) @@ -110,7 +110,7 @@ object SeqView { @SerialVersionUID(3L) class TakeRight[+A](underlying: SomeSeqOps[A]^, n: Int) extends View.TakeRight(underlying, n) with SeqView[A] { - private[this] val delta = (underlying.size - (n max 0)) max 0 + private val delta = (underlying.size - (n max 0)) max 0 def length = underlying.size - delta @throws[IndexOutOfBoundsException] def apply(i: Int) = underlying.apply(i + delta) @@ -126,7 +126,7 @@ object SeqView { @SerialVersionUID(3L) class DropRight[A](underlying: SomeSeqOps[A]^, n: Int) extends View.DropRight[A](underlying, n) with SeqView[A] { - private[this] val len = (underlying.size - (n max 0)) max 0 + private val len = (underlying.size - (n max 0)) max 0 def length = len @throws[IndexOutOfBoundsException] def apply(i: Int) = underlying.apply(i) @@ -134,7 +134,7 @@ object SeqView { @SerialVersionUID(3L) class Sorted[A, B >: A] private (underlying_ : SomeSeqOps[A]^, - private[this] val len: Int, + private val len: Int, ord: Ordering[B]) extends SeqView[A] { outer: Sorted[A, B]^ => @@ -146,8 +146,8 @@ object SeqView { def this(underlying: SomeSeqOps[A]^, ord: Ordering[B]) = this(underlying, underlying.length, ord) @SerialVersionUID(3L) - private[this] class ReverseSorted extends SeqView[A] { - private[this] lazy val _reversed = new SeqView.Reverse(_sorted) + private class ReverseSorted extends SeqView[A] { + private lazy val _reversed = new SeqView.Reverse(_sorted) def apply(i: Int): A = _reversed.apply(i) def length: Int = len @@ -164,9 +164,9 @@ object SeqView { else new Sorted(elems, len, ord1) } - @volatile private[this] var evaluated = false + @volatile private var evaluated = false - private[this] lazy val _sorted: Seq[A] = { + private lazy val _sorted: Seq[A] = { val res = { val len = this.len if (len == 0) Nil @@ -192,7 +192,7 @@ object SeqView { res } - private[this] def elems: SomeSeqOps[A]^{this} = { + private def elems: SomeSeqOps[A]^{this} = { if (evaluated) _sorted else underlying } diff --git a/library/src/scala/collection/Set.scala b/library/src/scala/collection/Set.scala index c5f879dc1644..87c1cdc20f91 100644 --- a/library/src/scala/collection/Set.scala +++ b/library/src/scala/collection/Set.scala @@ -79,7 +79,7 @@ trait Set[A] override def iterableFactory: IterableFactory[Set] = Set @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix: String = "Set" + override protected def stringPrefix: String = "Set" override def toString(): String = super[Iterable].toString() // Because `Function1` overrides `toString` too } @@ -128,9 +128,9 @@ transparent trait SetOps[A, +CC[_], +C <: SetOps[A, CC, C]] * @return the iterator. */ def subsets(): Iterator[C] = new AbstractIterator[C] { - private[this] val elms = SetOps.this.to(IndexedSeq) - private[this] var len = 0 - private[this] var itr: Iterator[C] = Iterator.empty + private val elms = SetOps.this.to(IndexedSeq) + private var len = 0 + private var itr: Iterator[C] = Iterator.empty def hasNext = len <= elms.size || itr.hasNext def next() = { @@ -154,8 +154,8 @@ transparent trait SetOps[A, +CC[_], +C <: SetOps[A, CC, C]] * */ private class SubsetsItr(elms: IndexedSeq[A], len: Int) extends AbstractIterator[C] { - private[this] val idxs = Array.range(0, len+1) - private[this] var _hasNext = true + private val idxs = Array.range(0, len+1) + private var _hasNext = true idxs(len) = elms.size def hasNext = _hasNext diff --git a/library/src/scala/collection/SortedMap.scala b/library/src/scala/collection/SortedMap.scala index 3a3b23be2409..591abfb83d8f 100644 --- a/library/src/scala/collection/SortedMap.scala +++ b/library/src/scala/collection/SortedMap.scala @@ -29,7 +29,7 @@ trait SortedMap[K, +V] def sortedMapFactory: SortedMapFactory[SortedMap] = SortedMap @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix: String = "SortedMap" + override protected def stringPrefix: String = "SortedMap" override def equals(that: Any): Boolean = that match { case _ if this eq that.asInstanceOf[AnyRef] => true @@ -50,7 +50,7 @@ trait SortedMap[K, +V] } } -transparent trait SortedMapOps[K, +V, +CC[X, Y] <: Map[X, Y] with SortedMapOps[X, Y, CC, _] with caps.Pure, +C <: SortedMapOps[K, V, CC, C]] +transparent trait SortedMapOps[K, +V, +CC[X, Y] <: Map[X, Y] & SortedMapOps[X, Y, CC, ?] & caps.Pure, +C <: SortedMapOps[K, V, CC, C]] extends MapOps[K, V, Map, C] with SortedOps[K, C] with caps.Pure { @@ -202,8 +202,8 @@ object SortedMapOps { * * @define coll sorted map collection */ - class WithFilter[K, +V, +IterableCC[_], +MapCC[X, Y] <: Map[X, Y], +CC[X, Y] <: Map[X, Y] with SortedMapOps[X, Y, CC, _]]( - self: SortedMapOps[K, V, CC, _] with MapOps[K, V, MapCC, _] with IterableOps[(K, V), IterableCC, _], + class WithFilter[K, +V, +IterableCC[_], +MapCC[X, Y] <: Map[X, Y], +CC[X, Y] <: Map[X, Y] & SortedMapOps[X, Y, CC, ?]]( + self: SortedMapOps[K, V, CC, ?] & MapOps[K, V, MapCC, ?] & IterableOps[(K, V), IterableCC, ?], p: ((K, V)) => Boolean ) extends MapOps.WithFilter[K, V, IterableCC, MapCC](self, p) { diff --git a/library/src/scala/collection/SortedSet.scala b/library/src/scala/collection/SortedSet.scala index ed3cfaee73da..4eb18c57520b 100644 --- a/library/src/scala/collection/SortedSet.scala +++ b/library/src/scala/collection/SortedSet.scala @@ -28,7 +28,7 @@ trait SortedSet[A] extends Set[A] def sortedIterableFactory: SortedIterableFactory[SortedSet] = SortedSet @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix: String = "SortedSet" + override protected def stringPrefix: String = "SortedSet" override def equals(that: Any): Boolean = that match { case _ if this eq that.asInstanceOf[AnyRef] => true @@ -172,7 +172,7 @@ object SortedSetOps { * @define coll sorted collection */ class WithFilter[+A, +IterableCC[_], +CC[X] <: SortedSet[X]]( - self: SortedSetOps[A, CC, _] with IterableOps[A, IterableCC, _], + self: SortedSetOps[A, CC, ?] & IterableOps[A, IterableCC, ?], p: A => Boolean ) extends IterableOps.WithFilter[A, IterableCC](self, p) { diff --git a/library/src/scala/collection/Stepper.scala b/library/src/scala/collection/Stepper.scala index d3f8c0d84518..859d87fdfad8 100644 --- a/library/src/scala/collection/Stepper.scala +++ b/library/src/scala/collection/Stepper.scala @@ -72,7 +72,7 @@ trait Stepper[@specialized(Double, Int, Long) +A] { * a [[java.util.Spliterator.OfInt]] (which is a `Spliterator[Integer]`) in the subclass [[IntStepper]] * (which is a `Stepper[Int]`). */ - def spliterator[B >: A]: Spliterator[_]^{this} + def spliterator[B >: A]: Spliterator[?]^{this} /** Returns a Java [[java.util.Iterator]] corresponding to this Stepper. * @@ -80,7 +80,7 @@ trait Stepper[@specialized(Double, Int, Long) +A] { * a [[java.util.PrimitiveIterator.OfInt]] (which is a `Iterator[Integer]`) in the subclass * [[IntStepper]] (which is a `Stepper[Int]`). */ - def javaIterator[B >: A]: JIterator[_]^{this} + def javaIterator[B >: A]: JIterator[?]^{this} /** Returns an [[Iterator]] corresponding to this Stepper. Note that Iterators corresponding to * primitive Steppers box the elements. @@ -198,7 +198,7 @@ trait AnyStepper[+A] extends Stepper[A] { object AnyStepper { class AnyStepperSpliterator[A](s: AnyStepper[A]^) extends Spliterator[A] { - def tryAdvance(c: Consumer[_ >: A]): Boolean = + def tryAdvance(c: Consumer[? >: A]): Boolean = if (s.hasStep) { c.accept(s.nextStep()); true } else false def trySplit(): Spliterator[A]^{this} | Null = { val sp = s.trySplit() @@ -207,18 +207,18 @@ object AnyStepper { def estimateSize(): Long = s.estimateSize def characteristics(): Int = s.characteristics // Override for efficiency: implement with hasStep / nextStep instead of tryAdvance - override def forEachRemaining(c: Consumer[_ >: A]): Unit = + override def forEachRemaining(c: Consumer[? >: A]): Unit = while (s.hasStep) { c.accept(s.nextStep()) } } def ofSeqDoubleStepper(st: DoubleStepper): AnyStepper[Double] = new BoxedDoubleStepper(st) - def ofParDoubleStepper(st: DoubleStepper with EfficientSplit): AnyStepper[Double] with EfficientSplit = new BoxedDoubleStepper(st) with EfficientSplit + def ofParDoubleStepper(st: DoubleStepper & EfficientSplit): AnyStepper[Double] & EfficientSplit = new BoxedDoubleStepper(st) with EfficientSplit def ofSeqIntStepper(st: IntStepper): AnyStepper[Int] = new BoxedIntStepper(st) - def ofParIntStepper(st: IntStepper with EfficientSplit): AnyStepper[Int] with EfficientSplit = new BoxedIntStepper(st) with EfficientSplit + def ofParIntStepper(st: IntStepper & EfficientSplit): AnyStepper[Int] & EfficientSplit = new BoxedIntStepper(st) with EfficientSplit def ofSeqLongStepper(st: LongStepper): AnyStepper[Long] = new BoxedLongStepper(st) - def ofParLongStepper(st: LongStepper with EfficientSplit): AnyStepper[Long] with EfficientSplit = new BoxedLongStepper(st) with EfficientSplit + def ofParLongStepper(st: LongStepper & EfficientSplit): AnyStepper[Long] & EfficientSplit = new BoxedLongStepper(st) with EfficientSplit private[collection] class BoxedDoubleStepper(st: DoubleStepper) extends AnyStepper[Double] { def hasStep: Boolean = st.hasStep @@ -270,7 +270,7 @@ object IntStepper { def tryAdvance(c: IntConsumer): Boolean = if (s.hasStep) { c.accept(s.nextStep()); true } else false // Override for efficiency: don't wrap the function and call the `tryAdvance` overload - override def tryAdvance(c: Consumer[_ >: jl.Integer]): Boolean = (c: AnyRef) match { + override def tryAdvance(c: Consumer[? >: jl.Integer]): Boolean = (c: AnyRef) match { case ic: IntConsumer => tryAdvance(ic) case _ => if (s.hasStep) { c.accept(jl.Integer.valueOf(s.nextStep())); true } else false } @@ -285,7 +285,7 @@ object IntStepper { override def forEachRemaining(c: IntConsumer): Unit = while (s.hasStep) { c.accept(s.nextStep()) } // Override for efficiency: implement with hasStep / nextStep instead of tryAdvance - override def forEachRemaining(c: Consumer[_ >: jl.Integer]): Unit = (c: AnyRef) match { + override def forEachRemaining(c: Consumer[? >: jl.Integer]): Unit = (c: AnyRef) match { case ic: IntConsumer => forEachRemaining(ic) case _ => while (s.hasStep) { c.accept(jl.Integer.valueOf(s.nextStep())) } } @@ -309,7 +309,7 @@ object DoubleStepper { def tryAdvance(c: DoubleConsumer): Boolean = if (s.hasStep) { c.accept(s.nextStep()); true } else false // Override for efficiency: don't wrap the function and call the `tryAdvance` overload - override def tryAdvance(c: Consumer[_ >: jl.Double]): Boolean = (c: AnyRef) match { + override def tryAdvance(c: Consumer[? >: jl.Double]): Boolean = (c: AnyRef) match { case ic: DoubleConsumer => tryAdvance(ic) case _ => if (s.hasStep) { c.accept(java.lang.Double.valueOf(s.nextStep())); true } else false } @@ -324,7 +324,7 @@ object DoubleStepper { override def forEachRemaining(c: DoubleConsumer): Unit = while (s.hasStep) { c.accept(s.nextStep()) } // Override for efficiency: implement with hasStep / nextStep instead of tryAdvance - override def forEachRemaining(c: Consumer[_ >: jl.Double]): Unit = (c: AnyRef) match { + override def forEachRemaining(c: Consumer[? >: jl.Double]): Unit = (c: AnyRef) match { case ic: DoubleConsumer => forEachRemaining(ic) case _ => while (s.hasStep) { c.accept(jl.Double.valueOf(s.nextStep())) } } @@ -348,7 +348,7 @@ object LongStepper { def tryAdvance(c: LongConsumer): Boolean = if (s.hasStep) { c.accept(s.nextStep()); true } else false // Override for efficiency: don't wrap the function and call the `tryAdvance` overload - override def tryAdvance(c: Consumer[_ >: jl.Long]): Boolean = (c: AnyRef) match { + override def tryAdvance(c: Consumer[? >: jl.Long]): Boolean = (c: AnyRef) match { case ic: LongConsumer => tryAdvance(ic) case _ => if (s.hasStep) { c.accept(java.lang.Long.valueOf(s.nextStep())); true } else false } @@ -363,7 +363,7 @@ object LongStepper { override def forEachRemaining(c: LongConsumer): Unit = while (s.hasStep) { c.accept(s.nextStep()) } // Override for efficiency: implement with hasStep / nextStep instead of tryAdvance - override def forEachRemaining(c: Consumer[_ >: jl.Long]): Unit = (c: AnyRef) match { + override def forEachRemaining(c: Consumer[? >: jl.Long]): Unit = (c: AnyRef) match { case ic: LongConsumer => forEachRemaining(ic) case _ => while (s.hasStep) { c.accept(jl.Long.valueOf(s.nextStep())) } } diff --git a/library/src/scala/collection/StepperShape.scala b/library/src/scala/collection/StepperShape.scala index 1b25d8758da0..5fc9ba823f95 100644 --- a/library/src/scala/collection/StepperShape.scala +++ b/library/src/scala/collection/StepperShape.scala @@ -22,7 +22,7 @@ import scala.collection.Stepper.EfficientSplit /** An implicit StepperShape instance is used in the [[IterableOnce.stepper]] to return a possibly * specialized Stepper `S` according to the element type `T`. */ -sealed trait StepperShape[-T, S <: Stepper[_]] { self => +sealed trait StepperShape[-T, S <: Stepper[?]] { self => /** Return the Int constant (as defined in the `StepperShape` companion object) for this `StepperShape`. */ def shape: StepperShape.Shape @@ -32,7 +32,7 @@ sealed trait StepperShape[-T, S <: Stepper[_]] { self => /** Create an unboxing primitive parallel (i.e. `with EfficientSplit`) Stepper from a boxed `AnyStepper`. * This is an identity operation for reference shapes. */ - def parUnbox(st: (AnyStepper[T] with EfficientSplit)^): (S with EfficientSplit)^{st} + def parUnbox(st: (AnyStepper[T] & EfficientSplit)^): (S & EfficientSplit)^{st} } object StepperShape extends StepperShapeLowPriority1 { @@ -55,49 +55,49 @@ object StepperShape extends StepperShapeLowPriority1 { implicit val intStepperShape: StepperShape[Int, IntStepper] = new StepperShape[Int, IntStepper] { def shape = IntShape def seqUnbox(st: AnyStepper[Int]^): IntStepper^{st} = new Stepper.UnboxingIntStepper(st) - def parUnbox(st: (AnyStepper[Int] with EfficientSplit)^): (IntStepper with EfficientSplit)^{st} = new Stepper.UnboxingIntStepper(st) with EfficientSplit + def parUnbox(st: (AnyStepper[Int] & EfficientSplit)^): (IntStepper & EfficientSplit)^{st} = new Stepper.UnboxingIntStepper(st) with EfficientSplit } implicit val jIntegerStepperShape: StepperShape[jl.Integer, IntStepper] = intStepperShape.asInstanceOf[StepperShape[jl.Integer, IntStepper]] implicit val longStepperShape: StepperShape[Long, LongStepper] = new StepperShape[Long, LongStepper] { def shape = LongShape def seqUnbox(st: AnyStepper[Long]^): LongStepper^{st} = new Stepper.UnboxingLongStepper(st) - def parUnbox(st: (AnyStepper[Long] with EfficientSplit)^): (LongStepper with EfficientSplit)^{st} = new Stepper.UnboxingLongStepper(st) with EfficientSplit + def parUnbox(st: (AnyStepper[Long] & EfficientSplit)^): (LongStepper & EfficientSplit)^{st} = new Stepper.UnboxingLongStepper(st) with EfficientSplit } implicit val jLongStepperShape: StepperShape[jl.Long, LongStepper] = longStepperShape.asInstanceOf[StepperShape[jl.Long, LongStepper]] implicit val doubleStepperShape: StepperShape[Double, DoubleStepper] = new StepperShape[Double, DoubleStepper] { def shape = DoubleShape def seqUnbox(st: AnyStepper[Double]^): DoubleStepper^{st} = new Stepper.UnboxingDoubleStepper(st) - def parUnbox(st: (AnyStepper[Double] with EfficientSplit)^): (DoubleStepper with EfficientSplit)^{st} = new Stepper.UnboxingDoubleStepper(st) with EfficientSplit + def parUnbox(st: (AnyStepper[Double] & EfficientSplit)^): (DoubleStepper & EfficientSplit)^{st} = new Stepper.UnboxingDoubleStepper(st) with EfficientSplit } implicit val jDoubleStepperShape: StepperShape[jl.Double, DoubleStepper] = doubleStepperShape.asInstanceOf[StepperShape[jl.Double, DoubleStepper]] implicit val byteStepperShape: StepperShape[Byte, IntStepper] = new StepperShape[Byte, IntStepper] { def shape = ByteShape def seqUnbox(st: AnyStepper[Byte]^): IntStepper^{st} = new Stepper.UnboxingByteStepper(st) - def parUnbox(st: (AnyStepper[Byte] with EfficientSplit)^): (IntStepper with EfficientSplit)^{st} = new Stepper.UnboxingByteStepper(st) with EfficientSplit + def parUnbox(st: (AnyStepper[Byte] & EfficientSplit)^): (IntStepper & EfficientSplit)^{st} = new Stepper.UnboxingByteStepper(st) with EfficientSplit } implicit val jByteStepperShape: StepperShape[jl.Byte, IntStepper] = byteStepperShape.asInstanceOf[StepperShape[jl.Byte, IntStepper]] implicit val shortStepperShape: StepperShape[Short, IntStepper] = new StepperShape[Short, IntStepper] { def shape = ShortShape def seqUnbox(st: AnyStepper[Short]^): IntStepper^{st} = new Stepper.UnboxingShortStepper(st) - def parUnbox(st: (AnyStepper[Short] with EfficientSplit)^): (IntStepper with EfficientSplit)^{st} = new Stepper.UnboxingShortStepper(st) with EfficientSplit + def parUnbox(st: (AnyStepper[Short] & EfficientSplit)^): (IntStepper & EfficientSplit)^{st} = new Stepper.UnboxingShortStepper(st) with EfficientSplit } implicit val jShortStepperShape: StepperShape[jl.Short, IntStepper] = shortStepperShape.asInstanceOf[StepperShape[jl.Short, IntStepper]] implicit val charStepperShape: StepperShape[Char, IntStepper] = new StepperShape[Char, IntStepper] { def shape = CharShape def seqUnbox(st: AnyStepper[Char]^): IntStepper^{st} = new Stepper.UnboxingCharStepper(st) - def parUnbox(st: (AnyStepper[Char] with EfficientSplit)^): (IntStepper with EfficientSplit)^{st} = new Stepper.UnboxingCharStepper(st) with EfficientSplit + def parUnbox(st: (AnyStepper[Char] & EfficientSplit)^): (IntStepper & EfficientSplit)^{st} = new Stepper.UnboxingCharStepper(st) with EfficientSplit } implicit val jCharacterStepperShape: StepperShape[jl.Character, IntStepper] = charStepperShape.asInstanceOf[StepperShape[jl.Character, IntStepper]] implicit val floatStepperShape: StepperShape[Float, DoubleStepper] = new StepperShape[Float, DoubleStepper] { def shape = FloatShape def seqUnbox(st: AnyStepper[Float]^): DoubleStepper^{st} = new Stepper.UnboxingFloatStepper(st) - def parUnbox(st: (AnyStepper[Float] with EfficientSplit)^): (DoubleStepper with EfficientSplit)^{st} = new Stepper.UnboxingFloatStepper(st) with EfficientSplit + def parUnbox(st: (AnyStepper[Float] & EfficientSplit)^): (DoubleStepper & EfficientSplit)^{st} = new Stepper.UnboxingFloatStepper(st) with EfficientSplit } implicit val jFloatStepperShape: StepperShape[jl.Float, DoubleStepper] = floatStepperShape.asInstanceOf[StepperShape[jl.Float, DoubleStepper]] } @@ -112,6 +112,6 @@ trait StepperShapeLowPriority2 { protected val anyStepperShapePrototype: StepperShape[AnyRef, Stepper[AnyRef]] = new StepperShape[AnyRef, Stepper[AnyRef]] { def shape = StepperShape.ReferenceShape def seqUnbox(st: AnyStepper[AnyRef]^): Stepper[AnyRef]^{st} = st - def parUnbox(st: (AnyStepper[AnyRef] with EfficientSplit)^): (Stepper[AnyRef] with EfficientSplit)^{st} = st + def parUnbox(st: (AnyStepper[AnyRef] & EfficientSplit)^): (Stepper[AnyRef] & EfficientSplit)^{st} = st } } diff --git a/library/src/scala/collection/StrictOptimizedIterableOps.scala b/library/src/scala/collection/StrictOptimizedIterableOps.scala index b89acb715cf7..75fe7edbdece 100644 --- a/library/src/scala/collection/StrictOptimizedIterableOps.scala +++ b/library/src/scala/collection/StrictOptimizedIterableOps.scala @@ -97,7 +97,7 @@ transparent trait StrictOptimizedIterableOps[+A, +CC[_], +C] * @tparam C2 Type of the resulting collection (e.g. `List[String]`) * @return The resulting collection */ - @inline protected[this] final def strictOptimizedMap[B, C2](b: mutable.Builder[B, C2], f: A => B): C2 = { + @inline protected final def strictOptimizedMap[B, C2](b: mutable.Builder[B, C2], f: A => B): C2 = { val it = iterator while (it.hasNext) { b += f(it.next()) @@ -115,7 +115,7 @@ transparent trait StrictOptimizedIterableOps[+A, +CC[_], +C] * @tparam C2 Type of the resulting collection (e.g. `List[String]`) * @return The resulting collection */ - @inline protected[this] final def strictOptimizedFlatMap[B, C2](b: mutable.Builder[B, C2]^, f: A => IterableOnce[B]^): C2 = { + @inline protected final def strictOptimizedFlatMap[B, C2](b: mutable.Builder[B, C2]^, f: A => IterableOnce[B]^): C2 = { val it = iterator while (it.hasNext) { b ++= f(it.next()) @@ -130,7 +130,7 @@ transparent trait StrictOptimizedIterableOps[+A, +CC[_], +C] * @tparam C2 Type of the resulting collection (e.g. `List[Int]`) * @return The resulting collection */ - @inline protected[this] final def strictOptimizedConcat[B >: A, C2](that: IterableOnce[B]^, b: mutable.Builder[B, C2]^): C2 = { + @inline protected final def strictOptimizedConcat[B >: A, C2](that: IterableOnce[B]^, b: mutable.Builder[B, C2]^): C2 = { b ++= this b ++= that b.result() @@ -146,7 +146,7 @@ transparent trait StrictOptimizedIterableOps[+A, +CC[_], +C] * @tparam C2 Type of the resulting collection (e.g. `List[String]`) * @return The resulting collection */ - @inline protected[this] final def strictOptimizedCollect[B, C2](b: mutable.Builder[B, C2]^, pf: PartialFunction[A, B]^): C2 = { + @inline protected final def strictOptimizedCollect[B, C2](b: mutable.Builder[B, C2]^, pf: PartialFunction[A, B]^): C2 = { val marker = Statics.pfMarker val it = iterator while (it.hasNext) { @@ -167,7 +167,7 @@ transparent trait StrictOptimizedIterableOps[+A, +CC[_], +C] * @tparam C2 Type of the resulting collection (e.g. `List[Int]`) * @return The resulting collection */ - @inline protected[this] final def strictOptimizedFlatten[B, C2](b: mutable.Builder[B, C2])(implicit toIterableOnce: A => IterableOnce[B]): C2 = { + @inline protected final def strictOptimizedFlatten[B, C2](b: mutable.Builder[B, C2])(implicit toIterableOnce: A => IterableOnce[B]): C2 = { val it = iterator while (it.hasNext) { b ++= toIterableOnce(it.next()) @@ -185,7 +185,7 @@ transparent trait StrictOptimizedIterableOps[+A, +CC[_], +C] * @tparam C2 Type of the resulting collection (e.g. `List[(Int, String)]`) * @return The resulting collection */ - @inline protected[this] final def strictOptimizedZip[B, C2](that: IterableOnce[B]^, b: mutable.Builder[(A, B), C2]^): C2 = { + @inline protected final def strictOptimizedZip[B, C2](that: IterableOnce[B]^, b: mutable.Builder[(A, B), C2]^): C2 = { val it1 = iterator val it2 = that.iterator while (it1.hasNext && it2.hasNext) { diff --git a/library/src/scala/collection/StrictOptimizedMapOps.scala b/library/src/scala/collection/StrictOptimizedMapOps.scala index b5eaa0d1638d..700d32fe4c0f 100644 --- a/library/src/scala/collection/StrictOptimizedMapOps.scala +++ b/library/src/scala/collection/StrictOptimizedMapOps.scala @@ -23,7 +23,7 @@ import language.experimental.captureChecking * @tparam CC Collection type constructor * @tparam C Collection type */ -transparent trait StrictOptimizedMapOps[K, +V, +CC[_, _] <: IterableOps[_, AnyConstr, _], +C] +transparent trait StrictOptimizedMapOps[K, +V, +CC[_, _] <: IterableOps[?, AnyConstr, ?], +C] extends MapOps[K, V, CC, C] with StrictOptimizedIterableOps[(K, V), Iterable, C] { diff --git a/library/src/scala/collection/StrictOptimizedSortedMapOps.scala b/library/src/scala/collection/StrictOptimizedSortedMapOps.scala index e9328dfb01e4..af10edf3218a 100644 --- a/library/src/scala/collection/StrictOptimizedSortedMapOps.scala +++ b/library/src/scala/collection/StrictOptimizedSortedMapOps.scala @@ -25,7 +25,7 @@ import scala.annotation.implicitNotFound * @tparam CC Collection type constructor * @tparam C Collection type */ -transparent trait StrictOptimizedSortedMapOps[K, +V, +CC[X, Y] <: Map[X, Y] with SortedMapOps[X, Y, CC, _], +C <: SortedMapOps[K, V, CC, C]] +transparent trait StrictOptimizedSortedMapOps[K, +V, +CC[X, Y] <: Map[X, Y] & SortedMapOps[X, Y, CC, ?], +C <: SortedMapOps[K, V, CC, C]] extends SortedMapOps[K, V, CC, C] with StrictOptimizedMapOps[K, V, Map, C] { diff --git a/library/src/scala/collection/StringOps.scala b/library/src/scala/collection/StringOps.scala index 9dea58b4f2ca..4445b27e9d07 100644 --- a/library/src/scala/collection/StringOps.scala +++ b/library/src/scala/collection/StringOps.scala @@ -31,8 +31,8 @@ object StringOps { private final val LF = 0x0A private final val CR = 0x0D - private class StringIterator(private[this] val s: String) extends AbstractIterator[Char] { - private[this] var pos = 0 + private class StringIterator(private val s: String) extends AbstractIterator[Char] { + private var pos = 0 def hasNext: Boolean = pos < s.length def next(): Char = { if (pos >= s.length) Iterator.empty.next() @@ -42,8 +42,8 @@ object StringOps { } } - private class ReverseIterator(private[this] val s: String) extends AbstractIterator[Char] { - private[this] var pos = s.length-1 + private class ReverseIterator(private val s: String) extends AbstractIterator[Char] { + private var pos = s.length-1 def hasNext: Boolean = pos >= 0 def next(): Char = { if (pos < 0) Iterator.empty.next() @@ -54,7 +54,7 @@ object StringOps { } private class GroupedIterator(s: String, groupSize: Int) extends AbstractIterator[String] { - private[this] var pos = 0 + private var pos = 0 def hasNext: Boolean = pos < s.length def next(): String = { if(pos >= s.length) Iterator.empty.next() @@ -209,7 +209,7 @@ final class StringOps(private val s: String) extends AnyVal { self => val dst = new Array[AnyRef](len) var i = 0 while (i < len) { - dst(i) = f(s charAt i).asInstanceOf[AnyRef] + dst(i) = f(s.charAt(i)).asInstanceOf[AnyRef] i += 1 } new ArraySeq.ofRef(dst).asInstanceOf[immutable.IndexedSeq[B]] @@ -226,7 +226,7 @@ final class StringOps(private val s: String) extends AnyVal { self => val dst = new Array[Char](len) var i = 0 while (i < len) { - dst(i) = f(s charAt i) + dst(i) = f(s.charAt(i)) i += 1 } new String(dst) @@ -262,7 +262,7 @@ final class StringOps(private val s: String) extends AnyVal { self => val sb = new JStringBuilder var i = 0 while (i < len) { - sb append f(s.charAt(i)) + sb.append(f(s.charAt(i))) i += 1 } sb.toString @@ -696,8 +696,8 @@ final class StringOps(private val s: String) extends AnyVal { self => def hasNext: Boolean = !done def next(): String = if (done) Iterator.empty.next() else advance() - private[this] val len = s.length - private[this] var index = 0 + private val len = s.length + private var index = 0 @inline private def done = index >= len private def advance(): String = { val start = index @@ -732,14 +732,14 @@ final class StringOps(private val s: String) extends AnyVal { self => * start with `prefix`, it is returned unchanged. */ def stripPrefix(prefix: String): String = - if (s startsWith prefix) s.substring(prefix.length) + if (s.startsWith(prefix)) s.substring(prefix.length) else s /** Returns this string with the given `suffix` stripped. If this string does not * end with `suffix`, it is returned unchanged. */ def stripSuffix(suffix: String): String = - if (s endsWith suffix) s.substring(0, s.length - suffix.length) + if (s.endsWith(suffix)) s.substring(0, s.length - suffix.length) else s /** Replace all literal occurrences of `literal` with the literal string `replacement`. @@ -778,7 +778,7 @@ final class StringOps(private val s: String) extends AnyVal { self => */ def stripMargin: String = stripMargin('|') - private[this] def escape(ch: Char): String = if ( + private def escape(ch: Char): String = if ( (ch >= 'a') && (ch <= 'z') || (ch >= 'A') && (ch <= 'Z') || (ch >= '0' && ch <= '9')) ch.toString @@ -861,7 +861,7 @@ final class StringOps(private val s: String) extends AnyVal { self => * @param groupNames The names of the groups in the pattern, in the order they appear. */ @deprecated("use inline group names like (?X) instead", "2.13.7") - def r(groupNames: String*): Regex = new Regex(s, groupNames: _*) + def r(groupNames: String*): Regex = new Regex(s, groupNames*) /** * @throws java.lang.IllegalArgumentException If the string does not contain a parsable `Boolean`. @@ -957,7 +957,7 @@ final class StringOps(private val s: String) extends AnyVal { self => */ def toDoubleOption: Option[Double] = StringParsers.parseDouble(s) - private[this] def toBooleanImpl(s: String): Boolean = + private def toBooleanImpl(s: String): Boolean = if (s == null) throw new IllegalArgumentException("For input string: \"null\"") else if (s.equalsIgnoreCase("true")) true else if (s.equalsIgnoreCase("false")) false @@ -967,7 +967,7 @@ final class StringOps(private val s: String) extends AnyVal { self => if (tag == ClassTag.Char) s.toCharArray.asInstanceOf[Array[B]] else new WrappedString(s).toArray[B] - private[this] def unwrapArg(arg: Any): AnyRef = arg match { + private def unwrapArg(arg: Any): AnyRef = arg match { case x: ScalaNumber => x.underlying() case x => x.asInstanceOf[AnyRef] } @@ -988,7 +988,7 @@ final class StringOps(private val s: String) extends AnyVal { self => * @throws java.util.IllegalFormatException if the format contains syntax or conversion errors */ def format(args: Any*): String = - java.lang.String.format(s, args.map(unwrapArg): _*) + java.lang.String.format(s, args.map(unwrapArg)*) /** Like `format(args*)` but takes an initial `Locale` parameter * which influences formatting as in `java.lang.String`'s format. @@ -1004,7 +1004,7 @@ final class StringOps(private val s: String) extends AnyVal { self => * @throws java.util.IllegalFormatException if the format contains syntax or conversion errors */ def formatLocal(l: java.util.Locale, args: Any*): String = - java.lang.String.format(l, s, args.map(unwrapArg): _*) + java.lang.String.format(l, s, args.map(unwrapArg)*) def compare(that: String): Int = s.compareTo(that) @@ -1158,16 +1158,16 @@ final class StringOps(private val s: String) extends AnyVal { self => /** Stepper can be used with Java 8 Streams. This method is equivalent to a call to * [[charStepper]]. See also [[codePointStepper]]. */ - @inline def stepper: IntStepper with EfficientSplit = charStepper + @inline def stepper: IntStepper & EfficientSplit = charStepper /** Steps over characters in this string. Values are packed in `Int` for efficiency * and compatibility with Java 8 Streams which have an efficient specialization for `Int`. */ - @inline def charStepper: IntStepper with EfficientSplit = new CharStringStepper(s, 0, s.length) + @inline def charStepper: IntStepper & EfficientSplit = new CharStringStepper(s, 0, s.length) /** Steps over code points in this string. */ - @inline def codePointStepper: IntStepper with EfficientSplit = new CodePointStringStepper(s, 0, s.length) + @inline def codePointStepper: IntStepper & EfficientSplit = new CodePointStringStepper(s, 0, s.length) /** Tests whether the string is not empty. */ @inline def nonEmpty: Boolean = !s.isEmpty @@ -1251,7 +1251,7 @@ final class StringOps(private val s: String) extends AnyVal { self => def inits: Iterator[String] = iterateUntilEmpty(_.init) // A helper for tails and inits. - private[this] def iterateUntilEmpty(f: String => String): Iterator[String]^{f} = + private def iterateUntilEmpty(f: String => String): Iterator[String]^{f} = Iterator.iterate(s)(f).takeWhile(x => !x.isEmpty) ++ Iterator.single("") /** Selects all chars of this string which satisfy a predicate. */ @@ -1531,7 +1531,7 @@ final class StringOps(private val s: String) extends AnyVal { self => * sorted according to the ordering `ord`. * @note $unicodeunaware */ - def sorted[B >: Char](implicit ord: Ordering[B]): String = new WrappedString(s).sorted(ord).unwrap + def sorted[B >: Char](implicit ord: Ordering[B]): String = new WrappedString(s).sorted(using ord).unwrap /** Sorts this string according to a comparison function. * @@ -1564,7 +1564,7 @@ final class StringOps(private val s: String) extends AnyVal { self => * `ord.lt(f(x), f(y))`. * @note $unicodeunaware */ - def sortBy[B](f: Char => B)(implicit ord: Ordering[B]): String = new WrappedString(s).sortBy(f)(ord).unwrap + def sortBy[B](f: Char => B)(implicit ord: Ordering[B]): String = new WrappedString(s).sortBy(f)(using ord).unwrap /** Partitions this string into a map of strings according to some discriminator function. * diff --git a/library/src/scala/collection/StringParsers.scala b/library/src/scala/collection/StringParsers.scala index 6c4807bf1929..ac147583c8fa 100644 --- a/library/src/scala/collection/StringParsers.scala +++ b/library/src/scala/collection/StringParsers.scala @@ -34,10 +34,10 @@ private[scala] object StringParsers { private final val POS = true @inline - private[this] final def decValue(ch: Char): Int = java.lang.Character.digit(ch, 10) + private final def decValue(ch: Char): Int = java.lang.Character.digit(ch, 10) @inline - private[this] final def stepToOverflow(from: String, len: Int, agg: Int, isPositive: Boolean, min: Int): Option[Int] = { + private final def stepToOverflow(from: String, len: Int, agg: Int, isPositive: Boolean, min: Int): Option[Int] = { @tailrec def rec(i: Int, agg: Int): Option[Int] = if (agg < min) None @@ -55,7 +55,7 @@ private[scala] object StringParsers { } @inline - private[this] final def isDigit(c: Char): Boolean = c >= '0' && c <= '9' + private final def isDigit(c: Char): Boolean = c >= '0' && c <= '9' //bool @inline diff --git a/library/src/scala/collection/View.scala b/library/src/scala/collection/View.scala index 0ea0459664bd..f55f2e07578f 100644 --- a/library/src/scala/collection/View.scala +++ b/library/src/scala/collection/View.scala @@ -38,7 +38,7 @@ trait View[+A] extends Iterable[A] with IterableOps[A, View, View[A]] with Itera override def toString: String = className + "()" @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix: String = "View" + override protected def stringPrefix: String = "View" @deprecated("Views no longer know about their underlying collection type; .force always returns an IndexedSeq", "2.13.0") @`inline` def force: IndexedSeq[A] = toIndexedSeq @@ -82,7 +82,7 @@ object View extends IterableFactory[View] { def newBuilder[A]: Builder[A, View[A]] = ArrayBuffer.newBuilder[A].mapResult(from) - override def apply[A](xs: A*): View[A] = new Elems(xs: _*) + override def apply[A](xs: A*): View[A] = new Elems(xs*) /** The empty view */ @SerialVersionUID(3L) @@ -141,7 +141,7 @@ object View extends IterableFactory[View] { } /** An `IterableOps` whose collection type and collection type constructor are unknown */ - type SomeIterableOps[A] = IterableOps[A, AnyConstr, _] + type SomeIterableOps[A] = IterableOps[A, AnyConstr, ?] /** A view that filters an underlying collection. */ @SerialVersionUID(3L) @@ -174,9 +174,9 @@ object View extends IterableFactory[View] { @SerialVersionUID(3L) class LeftPartitionMapped[A, A1, A2](underlying: SomeIterableOps[A]^, f: A => Either[A1, A2]) extends AbstractView[A1] { def iterator: AbstractIterator[A1]^{this} = new AbstractIterator[A1] { - private[this] val self = underlying.iterator - private[this] var hd: A1 = _ - private[this] var hdDefined: Boolean = false + private val self = underlying.iterator + private var hd: A1 = compiletime.uninitialized + private var hdDefined: Boolean = false def hasNext = hdDefined || { @tailrec def findNext(): Boolean = @@ -199,9 +199,9 @@ object View extends IterableFactory[View] { @SerialVersionUID(3L) class RightPartitionMapped[A, A1, A2](underlying: SomeIterableOps[A]^, f: A => Either[A1, A2]) extends AbstractView[A2] { def iterator: AbstractIterator[A2]^{this} = new AbstractIterator[A2] { - private[this] val self = underlying.iterator - private[this] var hd: A2 = _ - private[this] var hdDefined: Boolean = false + private val self = underlying.iterator + private var hd: A2 = compiletime.uninitialized + private var hdDefined: Boolean = false def hasNext = hdDefined || { @tailrec def findNext(): Boolean = @@ -395,8 +395,8 @@ object View extends IterableFactory[View] { @SerialVersionUID(3L) class Updated[A](underlying: SomeIterableOps[A]^, index: Int, elem: A) extends AbstractView[A] { def iterator: Iterator[A]^{underlying} = new AbstractIterator[A] { - private[this] val it = underlying.iterator - private[this] var i = 0 + private val it = underlying.iterator + private var i = 0 def next(): A = { val value = if (i == index) { it.next(); elem } else it.next() i += 1 @@ -450,11 +450,11 @@ object View extends IterableFactory[View] { else new TakeRightIterator[A](it, n) } - private final class TakeRightIterator[A](private[this] var underlying: Iterator[A]^, maxlen: Int) extends AbstractIterator[A] { - private[this] var len: Int = -1 - private[this] var pos: Int = 0 + private final class TakeRightIterator[A](private var underlying: Iterator[A]^, maxlen: Int) extends AbstractIterator[A] { + private var len: Int = -1 + private var pos: Int = 0 @annotation.stableNull - private[this] var buf: ArrayBuffer[AnyRef] | Null = _ + private var buf: ArrayBuffer[AnyRef] | Null = compiletime.uninitialized def init(): Unit = if(buf eq null) { buf = new ArrayBuffer[AnyRef](maxlen min 256) len = 0 @@ -506,11 +506,11 @@ object View extends IterableFactory[View] { } } - private final class DropRightIterator[A](private[this] var underlying: Iterator[A]^, maxlen: Int) extends AbstractIterator[A] { - private[this] var len: Int = -1 // known size or -1 if the end of `underlying` has not been seen yet - private[this] var pos: Int = 0 + private final class DropRightIterator[A](private var underlying: Iterator[A]^, maxlen: Int) extends AbstractIterator[A] { + private var len: Int = -1 // known size or -1 if the end of `underlying` has not been seen yet + private var pos: Int = 0 @annotation.stableNull - private[this] var buf: ArrayBuffer[AnyRef] | Null = _ + private var buf: ArrayBuffer[AnyRef] | Null = compiletime.uninitialized def init(): Unit = if(buf eq null) { buf = new ArrayBuffer[AnyRef](maxlen min 256) while(pos < maxlen && underlying.hasNext) { diff --git a/library/src/scala/collection/concurrent/TrieMap.scala b/library/src/scala/collection/concurrent/TrieMap.scala index 875ba45c9f49..98641bcc680d 100644 --- a/library/src/scala/collection/concurrent/TrieMap.scala +++ b/library/src/scala/collection/concurrent/TrieMap.scala @@ -368,7 +368,7 @@ private[collection] final class INode[K, V](bn: MainNode[K, V] | Null, g: Gen, e if (parent ne null) { // never tomb at root val n = GCAS_READ(ct) - if (n.isInstanceOf[TNode[_, _]]) + if (n.isInstanceOf[TNode[?, ?]]) cleanParent(n) } @@ -697,10 +697,10 @@ final class TrieMap[K, V] private (r: AnyRef, rtupd: AtomicReferenceFieldUpdater with scala.collection.MapFactoryDefaults[K, V, TrieMap, mutable.Iterable] with DefaultSerializable { - private[this] var hashingobj = if (hashf.isInstanceOf[Hashing.Default[_]]) new TrieMap.MangledHashing[K] else hashf - private[this] var equalityobj = ef + private var hashingobj = if (hashf.isInstanceOf[Hashing.Default[?]]) new TrieMap.MangledHashing[K] else hashf + private var equalityobj = ef @transient - private[this] var rootupdater: AtomicReferenceFieldUpdater[TrieMap[K, V], AnyRef] | Null = rtupd + private var rootupdater: AtomicReferenceFieldUpdater[TrieMap[K, V], AnyRef] | Null = rtupd def hashing = hashingobj def equality = equalityobj @volatile private var root = r @@ -1034,7 +1034,7 @@ final class TrieMap[K, V] private (r: AnyRef, rtupd: AtomicReferenceFieldUpdater else RDCSS_READ_ROOT().knownSize(this) override def isEmpty: Boolean = (if (nonReadOnly) readOnlySnapshot() else this).sizeIs == 0 // sizeIs checks knownSize - override protected[this] def className = "TrieMap" + override protected def className = "TrieMap" override def lastOption: Option[(K, V)] = if (isEmpty) None else Try(last).toOption } @@ -1050,7 +1050,7 @@ object TrieMap extends MapFactory[TrieMap] { def newBuilder[K, V]: mutable.GrowableBuilder[(K, V), TrieMap[K, V]] = new GrowableBuilder(empty[K, V]) @transient - val inodeupdater: AtomicReferenceFieldUpdater[INodeBase[_, _], MainNode[_, _]] = AtomicReferenceFieldUpdater.newUpdater(classOf[INodeBase[_, _]], classOf[MainNode[_, _]], "mainnode") + val inodeupdater: AtomicReferenceFieldUpdater[INodeBase[?, ?], MainNode[?, ?]] = AtomicReferenceFieldUpdater.newUpdater(classOf[INodeBase[?, ?]], classOf[MainNode[?, ?]], "mainnode") class MangledHashing[K] extends Hashing[K] { def hash(k: K): Int = scala.util.hashing.byteswap32(k.##) diff --git a/library/src/scala/collection/convert/JavaCollectionWrappers.scala b/library/src/scala/collection/convert/JavaCollectionWrappers.scala index d131a185c736..d4d6135eaaac 100644 --- a/library/src/scala/collection/convert/JavaCollectionWrappers.scala +++ b/library/src/scala/collection/convert/JavaCollectionWrappers.scala @@ -150,8 +150,8 @@ private[collection] object JavaCollectionWrappers extends Serializable { override def iterator: Iterator[A] = underlying.iterator.asScala def apply(i: Int): A = underlying.get(i) def update(i: Int, elem: A) = underlying.set(i, elem) - def prepend(elem: A) = { underlying.subList(0, 0) add elem; this } - def addOne(elem: A): this.type = { underlying add elem; this } + def prepend(elem: A) = { underlying.subList(0, 0).add(elem); this } + def addOne(elem: A): this.type = { underlying.add(elem); this } def insert(idx: Int,elem: A): Unit = underlying.subList(0, idx).add(elem) def insertAll(i: Int, elems: IterableOnce[A]^) = { val ins = underlying.subList(0, i) @@ -228,10 +228,10 @@ private[collection] object JavaCollectionWrappers extends Serializable { def contains(elem: A): Boolean = underlying.contains(elem) - def addOne(elem: A): this.type = { underlying add elem; this } - def subtractOne(elem: A): this.type = { underlying remove elem; this } + def addOne(elem: A): this.type = { underlying.add(elem); this } + def subtractOne(elem: A): this.type = { underlying.remove(elem); this } - override def remove(elem: A): Boolean = underlying remove elem + override def remove(elem: A): Boolean = underlying.remove(elem) override def clear(): Unit = { underlying.clear() @@ -348,7 +348,7 @@ private[collection] object JavaCollectionWrappers extends Serializable { extends mutable.AbstractMap[K, V] with JMapWrapperLike[K, V, mutable.Map, mutable.Map[K, V]] with Serializable - trait JMapWrapperLike[K, V, +CC[X, Y] <: mutable.MapOps[X, Y, CC, _], +C <: mutable.MapOps[K, V, CC, C]] + trait JMapWrapperLike[K, V, +CC[X, Y] <: mutable.MapOps[X, Y, CC, ?], +C <: mutable.MapOps[K, V, CC, C]] extends mutable.MapOps[K, V, CC, C] with StrictOptimizedMapOps[K, V, CC, C] with StrictOptimizedIterableOps[(K, V), mutable.Iterable, C] { @@ -375,7 +375,7 @@ private[collection] object JavaCollectionWrappers extends Serializable { } def addOne(kv: (K, V)): this.type = { underlying.put(kv._1, kv._2); this } - def subtractOne(key: K): this.type = { underlying remove key; this } + def subtractOne(key: K): this.type = { underlying.remove(key); this } // support Some(null) if currently bound to null override def put(k: K, v: V): Option[V] = @@ -479,7 +479,7 @@ private[collection] object JavaCollectionWrappers extends Serializable { extends AbstractJMapWrapper[K, V] with concurrent.Map[K, V] { - override def get(k: K) = Option(underlying get k) + override def get(k: K) = Option(underlying.get(k)) override def getOrElseUpdate(key: K, op: => V): V = underlying.computeIfAbsent(key, _ => op) match { @@ -561,17 +561,17 @@ private[collection] object JavaCollectionWrappers extends Serializable { override def isEmpty: Boolean = underlying.isEmpty override def knownSize: Int = if (underlying.isEmpty) 0 else super.knownSize - def get(k: K) = Option(underlying get k) + def get(k: K) = Option(underlying.get(k)) def addOne(kv: (K, V)): this.type = { underlying.put(kv._1, kv._2); this } - def subtractOne(key: K): this.type = { underlying remove key; this } + def subtractOne(key: K): this.type = { underlying.remove(key); this } override def put(k: K, v: V): Option[V] = Option(underlying.put(k, v)) override def update(k: K, v: V): Unit = { underlying.put(k, v) } - override def remove(k: K): Option[V] = Option(underlying remove k) - def iterator = underlying.keys.asScala map (k => (k, underlying get k)) + override def remove(k: K): Option[V] = Option(underlying.remove(k)) + def iterator = underlying.keys.asScala map (k => (k, underlying.get(k))) override def clear() = iterator.foreach(entry => underlying.remove(entry._1)) @@ -590,12 +590,12 @@ private[collection] object JavaCollectionWrappers extends Serializable { override def isEmpty: Boolean = underlying.isEmpty override def knownSize: Int = size def get(k: String) = { - val v = underlying get k + val v = underlying.get(k) if (v != null) Some(v.asInstanceOf[String]) else None } def addOne(kv: (String, String)): this.type = { underlying.put(kv._1, kv._2); this } - def subtractOne(key: String): this.type = { underlying remove key; this } + def subtractOne(key: String): this.type = { underlying.remove(key); this } override def put(k: String, v: String): Option[String] = { val r = underlying.put(k, v) @@ -605,7 +605,7 @@ private[collection] object JavaCollectionWrappers extends Serializable { override def update(k: String, v: String): Unit = { underlying.put(k, v) } override def remove(k: String): Option[String] = { - val r = underlying remove k + val r = underlying.remove(k) if (r != null) Some(r.asInstanceOf[String]) else None } diff --git a/library/src/scala/collection/convert/StreamExtensions.scala b/library/src/scala/collection/convert/StreamExtensions.scala index ca161d45d83a..617f7a8b186a 100644 --- a/library/src/scala/collection/convert/StreamExtensions.scala +++ b/library/src/scala/collection/convert/StreamExtensions.scala @@ -38,21 +38,21 @@ trait StreamExtensions { * collection contains primitive values, a corresponding specialized Stream is returned (e.g., * [[java.util.stream.IntStream `IntStream`]]). */ - def asJavaSeqStream[S <: BaseStream[_, _], St <: Stepper[_]](implicit s: StreamShape[A, S, St], st: StepperShape[A, St]): S = + def asJavaSeqStream[S <: BaseStream[?, ?], St <: Stepper[?]](implicit s: StreamShape[A, S, St], st: StepperShape[A, St]): S = s.fromStepper(cc.stepper, par = false) } // Not `CC[X] <: IterableOnce[X]`, but `C` with an extra constraint, to support non-parametric classes like IntAccumulator - implicit class IterableNonGenericHasParStream[A, C <: IterableOnce[_]](c: C)(implicit ev: C <:< IterableOnce[A]) { + implicit class IterableNonGenericHasParStream[A, C <: IterableOnce[?]](c: C)(implicit ev: C <:< IterableOnce[A]) { private type IterableOnceWithEfficientStepper = IterableOnce[A] { - def stepper[S <: Stepper[_]](implicit shape : StepperShape[A, S]) : S with EfficientSplit + def stepper[S <: Stepper[?]](implicit shape : StepperShape[A, S]) : S & EfficientSplit } /** Create a parallel [[java.util.stream.Stream Java Stream]] for this collection. If the * collection contains primitive values, a corresponding specialized Stream is returned (e.g., * [[java.util.stream.IntStream `IntStream`]]). */ - def asJavaParStream[S <: BaseStream[_, _], St <: Stepper[_]](implicit + def asJavaParStream[S <: BaseStream[?, ?], St <: Stepper[?]](implicit s: StreamShape[A, S, St], st: StepperShape[A, St], @implicitNotFound("`parStream` can only be called on collections where `stepper` returns a `Stepper with EfficientSplit`") @@ -62,40 +62,40 @@ trait StreamExtensions { // maps - implicit class MapHasSeqKeyValueStream[K, V, CC[X, Y] <: collection.MapOps[X, Y, collection.Map, _]](cc: CC[K, V]) { + implicit class MapHasSeqKeyValueStream[K, V, CC[X, Y] <: collection.MapOps[X, Y, collection.Map, ?]](cc: CC[K, V]) { /** Create a sequential [[java.util.stream.Stream Java Stream]] for the keys of this map. If * the keys are primitive values, a corresponding specialized Stream is returned (e.g., * [[java.util.stream.IntStream `IntStream`]]). */ - def asJavaSeqKeyStream[S <: BaseStream[_, _], St <: Stepper[_]](implicit s: StreamShape[K, S, St], st: StepperShape[K, St]): S = + def asJavaSeqKeyStream[S <: BaseStream[?, ?], St <: Stepper[?]](implicit s: StreamShape[K, S, St], st: StepperShape[K, St]): S = s.fromStepper(cc.keyStepper, par = false) /** Create a sequential [[java.util.stream.Stream Java Stream]] for the values of this map. If * the values are primitives, a corresponding specialized Stream is returned (e.g., * [[java.util.stream.IntStream `IntStream`]]). */ - def asJavaSeqValueStream[S <: BaseStream[_, _], St <: Stepper[_]](implicit s: StreamShape[V, S, St], st: StepperShape[V, St]): S = + def asJavaSeqValueStream[S <: BaseStream[?, ?], St <: Stepper[?]](implicit s: StreamShape[V, S, St], st: StepperShape[V, St]): S = s.fromStepper(cc.valueStepper, par = false) // The asJavaSeqStream extension method for IterableOnce doesn't apply because its `CC` takes a single type parameter, whereas the one here takes two /** Create a sequential [[java.util.stream.Stream Java Stream]] for the `(key, value)` pairs of * this map. */ - def asJavaSeqStream[S <: BaseStream[_, _], St <: Stepper[_]](implicit s: StreamShape[(K, V), S, St], st: StepperShape[(K, V), St]): S = + def asJavaSeqStream[S <: BaseStream[?, ?], St <: Stepper[?]](implicit s: StreamShape[(K, V), S, St], st: StepperShape[(K, V), St]): S = s.fromStepper(cc.stepper, par = false) } - implicit class MapHasParKeyValueStream[K, V, CC[X, Y] <: collection.MapOps[X, Y, collection.Map, _]](cc: CC[K, V]) { - private type MapOpsWithEfficientKeyStepper = collection.MapOps[K, V, collection.Map, _] { def keyStepper[S <: Stepper[_]](implicit shape : StepperShape[K, S]) : S with EfficientSplit } - private type MapOpsWithEfficientValueStepper = collection.MapOps[K, V, collection.Map, _] { def valueStepper[S <: Stepper[_]](implicit shape : StepperShape[V, S]) : S with EfficientSplit } - private type MapOpsWithEfficientStepper = collection.MapOps[K, V, collection.Map, _] { def stepper[S <: Stepper[_]](implicit shape : StepperShape[(K, V), S]) : S with EfficientSplit } + implicit class MapHasParKeyValueStream[K, V, CC[X, Y] <: collection.MapOps[X, Y, collection.Map, ?]](cc: CC[K, V]) { + private type MapOpsWithEfficientKeyStepper = collection.MapOps[K, V, collection.Map, ?] { def keyStepper[S <: Stepper[?]](implicit shape : StepperShape[K, S]) : S & EfficientSplit } + private type MapOpsWithEfficientValueStepper = collection.MapOps[K, V, collection.Map, ?] { def valueStepper[S <: Stepper[?]](implicit shape : StepperShape[V, S]) : S & EfficientSplit } + private type MapOpsWithEfficientStepper = collection.MapOps[K, V, collection.Map, ?] { def stepper[S <: Stepper[?]](implicit shape : StepperShape[(K, V), S]) : S & EfficientSplit } /** Create a parallel [[java.util.stream.Stream Java Stream]] for the keys of this map. If * the keys are primitive values, a corresponding specialized Stream is returned (e.g., * [[java.util.stream.IntStream `IntStream`]]). */ - def asJavaParKeyStream[S <: BaseStream[_, _], St <: Stepper[_]](implicit + def asJavaParKeyStream[S <: BaseStream[?, ?], St <: Stepper[?]](implicit s: StreamShape[K, S, St], st: StepperShape[K, St], @implicitNotFound("parKeyStream can only be called on maps where `keyStepper` returns a `Stepper with EfficientSplit`") @@ -106,7 +106,7 @@ trait StreamExtensions { * the values are primitives, a corresponding specialized Stream is returned (e.g., * [[java.util.stream.IntStream `IntStream`]]). */ - def asJavaParValueStream[S <: BaseStream[_, _], St <: Stepper[_]](implicit + def asJavaParValueStream[S <: BaseStream[?, ?], St <: Stepper[?]](implicit s: StreamShape[V, S, St], st: StepperShape[V, St], @implicitNotFound("parValueStream can only be called on maps where `valueStepper` returns a `Stepper with EfficientSplit`") @@ -117,7 +117,7 @@ trait StreamExtensions { /** Create a parallel [[java.util.stream.Stream Java Stream]] for the `(key, value)` pairs of * this map. */ - def asJavaParStream[S <: BaseStream[_, _], St <: Stepper[_]](implicit + def asJavaParStream[S <: BaseStream[?, ?], St <: Stepper[?]](implicit s: StreamShape[(K, V), S, St], st: StepperShape[(K, V), St], @implicitNotFound("parStream can only be called on maps where `stepper` returns a `Stepper with EfficientSplit`") @@ -132,7 +132,7 @@ trait StreamExtensions { * stepper yields primitive values, a corresponding specialized Stream is returned (e.g., * [[java.util.stream.IntStream `IntStream`]]). */ - def asJavaSeqStream[S <: BaseStream[_, _], St <: Stepper[_]](implicit s: StreamShape[A, S, St], st: StepperShape[A, St]): S = { + def asJavaSeqStream[S <: BaseStream[?, ?], St <: Stepper[?]](implicit s: StreamShape[A, S, St], st: StepperShape[A, St]): S = { val sStepper = stepper match { case as: AnyStepper[A] => st.seqUnbox(as) case _ => stepper.asInstanceOf[St] @@ -141,14 +141,14 @@ trait StreamExtensions { } } - implicit class StepperHasParStream[A](stepper: Stepper[A] with EfficientSplit) { + implicit class StepperHasParStream[A](stepper: Stepper[A] & EfficientSplit) { /** Create a parallel [[java.util.stream.Stream Java Stream]] for this stepper. If the * stepper yields primitive values, a corresponding specialized Stream is returned (e.g., * [[java.util.stream.IntStream `IntStream`]]). */ - def asJavaParStream[S <: BaseStream[_, _], St <: Stepper[_]](implicit s: StreamShape[A, S, St], st: StepperShape[A, St]): S = { + def asJavaParStream[S <: BaseStream[?, ?], St <: Stepper[?]](implicit s: StreamShape[A, S, St], st: StepperShape[A, St]): S = { val sStepper = stepper match { - case as: AnyStepper[A] with EfficientSplit => st.parUnbox(as) + case as: (AnyStepper[A] & EfficientSplit) => st.parUnbox(as) case _ => stepper.asInstanceOf[St] } s.fromStepper(sStepper, par = true) @@ -368,7 +368,7 @@ object StreamExtensions { * Stream and Stepper types. This is used in `asJavaStream` extension methods to create * generic or primitive streams according to the element type. */ - sealed trait StreamShape[T, S <: BaseStream[_, _], St <: Stepper[_]] { + sealed trait StreamShape[T, S <: BaseStream[?, ?], St <: Stepper[?]] { final def fromStepper(st: St, par: Boolean): S = mkStream(st, par) protected def mkStream(st: St, par: Boolean): S } @@ -412,7 +412,7 @@ object StreamExtensions { // reference implicit def anyStreamShape[T]: StreamShape[T, Stream[T], Stepper[T]] = anyStreamShapePrototype.asInstanceOf[StreamShape[T, Stream[T], Stepper[T]]] - private[this] val anyStreamShapePrototype: StreamShape[AnyRef, Stream[AnyRef], Stepper[AnyRef]] = new StreamShape[AnyRef, Stream[AnyRef], Stepper[AnyRef]] { + private val anyStreamShapePrototype: StreamShape[AnyRef, Stream[AnyRef], Stepper[AnyRef]] = new StreamShape[AnyRef, Stream[AnyRef], Stepper[AnyRef]] { def mkStream(s: Stepper[AnyRef], par: Boolean): Stream[AnyRef] = StreamSupport.stream(s.spliterator.asInstanceOf[Spliterator[AnyRef]], par) } } diff --git a/library/src/scala/collection/convert/impl/BinaryTreeStepper.scala b/library/src/scala/collection/convert/impl/BinaryTreeStepper.scala index d736044f4f90..861ea53f8ba5 100644 --- a/library/src/scala/collection/convert/impl/BinaryTreeStepper.scala +++ b/library/src/scala/collection/convert/impl/BinaryTreeStepper.scala @@ -46,7 +46,7 @@ private[collection] object BinaryTreeStepper { * Subclasses should allow this class to do all the work of maintaining state; `next` should simply * reduce `maxLength` by one, and consume `myCurrent` and set it to `null` if `hasNext` is true. */ -private[collection] abstract class BinaryTreeStepperBase[A, T <: AnyRef, Sub, Semi <: Sub with BinaryTreeStepperBase[A, T, _, _]]( +private[collection] abstract class BinaryTreeStepperBase[A, T <: AnyRef, Sub, Semi <: Sub & BinaryTreeStepperBase[A, T, ?, ?]]( protected var maxLength: Int, protected var myCurrent: T | Null, protected var stack: Array[AnyRef | Null], protected var index: Int, protected val left: T => T | Null, protected val right: T => T | Null ) diff --git a/library/src/scala/collection/convert/impl/BitSetStepper.scala b/library/src/scala/collection/convert/impl/BitSetStepper.scala index 70d59d2d2555..f7132e946b88 100644 --- a/library/src/scala/collection/convert/impl/BitSetStepper.scala +++ b/library/src/scala/collection/convert/impl/BitSetStepper.scala @@ -20,7 +20,7 @@ import scala.collection.{BitSetOps, IntStepper, Stepper} private[collection] final class BitSetStepper( @annotation.stableNull - private var underlying: BitSetOps[_] | Null, + private var underlying: BitSetOps[?] | Null, private var cache0: Long, private var cache1: Long, _i0: Int, _iN: Int, private var cacheIndex: Int @@ -92,7 +92,7 @@ with IntStepper { } @annotation.tailrec - private[this] def scanLong(bits: Long, from: Int): Int = + private def scanLong(bits: Long, from: Int): Int = if (from >= WordLength) -1 else if ((bits & (1L << from)) != 0) from else scanLong(bits, from + 1) @@ -108,7 +108,7 @@ with IntStepper { } private[collection] object BitSetStepper { - def from(bs: scala.collection.BitSetOps[_]): IntStepper with EfficientSplit = + def from(bs: scala.collection.BitSetOps[?]): IntStepper & EfficientSplit = new BitSetStepper( if (bs.nwords <= 2) null else bs, if (bs.nwords <= 0) -1L else bs.word(0), diff --git a/library/src/scala/collection/convert/impl/ChampStepper.scala b/library/src/scala/collection/convert/impl/ChampStepper.scala index 05589f1ee04d..ba22bfd89582 100644 --- a/library/src/scala/collection/convert/impl/ChampStepper.scala +++ b/library/src/scala/collection/convert/impl/ChampStepper.scala @@ -23,7 +23,7 @@ import scala.collection.immutable.Node * to the end of all trees. */ private[collection] abstract class ChampStepperBase[ - A, T <: Node[T], Sub, Semi <: Sub with ChampStepperBase[A, T, _, _] + A, T <: Node[T], Sub, Semi <: Sub & ChampStepperBase[A, T, ?, ?] ](protected var maxSize: Int) extends EfficientSplit { import Node.MaxDepth @@ -32,11 +32,11 @@ extends EfficientSplit { protected var currentValueCursor: Int = 0 protected var currentValueLength: Int = 0 - protected var currentValueNode: T = _ + protected var currentValueNode: T = compiletime.uninitialized private var currentStackLevel: Int = -1 - private var nodeCursorsAndLengths: Array[Int] = _ - private var nodes: Array[T] = _ + private var nodeCursorsAndLengths: Array[Int] = compiletime.uninitialized + private var nodes: Array[T] = compiletime.uninitialized private def initNodes(): Unit = { if (nodeCursorsAndLengths eq null) { diff --git a/library/src/scala/collection/convert/impl/IndexedSeqStepper.scala b/library/src/scala/collection/convert/impl/IndexedSeqStepper.scala index 5e4717c55fe1..3ab2f4ab135f 100644 --- a/library/src/scala/collection/convert/impl/IndexedSeqStepper.scala +++ b/library/src/scala/collection/convert/impl/IndexedSeqStepper.scala @@ -16,28 +16,28 @@ package impl import scala.language.`2.13` import scala.collection._ -private[collection] class AnyIndexedSeqStepper[A](underlying: collection.IndexedSeqOps[A, AnyConstr, _], _i0: Int, _iN: Int) +private[collection] class AnyIndexedSeqStepper[A](underlying: collection.IndexedSeqOps[A, AnyConstr, ?], _i0: Int, _iN: Int) extends IndexedStepperBase[AnyStepper[A], AnyIndexedSeqStepper[A]](_i0, _iN) with AnyStepper[A] { def nextStep(): A = if (hasStep) { val j = i0; i0 += 1; underlying(j) } else Stepper.throwNSEE() protected def semiclone(half: Int): AnyIndexedSeqStepper[A] = new AnyIndexedSeqStepper[A](underlying, i0, half) } -private[collection] class DoubleIndexedSeqStepper[CC <: collection.IndexedSeqOps[Double, AnyConstr, _]](underlying: CC, _i0: Int, _iN: Int) +private[collection] class DoubleIndexedSeqStepper[CC <: collection.IndexedSeqOps[Double, AnyConstr, ?]](underlying: CC, _i0: Int, _iN: Int) extends IndexedStepperBase[DoubleStepper, DoubleIndexedSeqStepper[CC]](_i0, _iN) with DoubleStepper { def nextStep(): Double = if (hasStep) { val j = i0; i0 += 1; underlying(j) } else Stepper.throwNSEE() protected def semiclone(half: Int): DoubleIndexedSeqStepper[CC] = new DoubleIndexedSeqStepper[CC](underlying, i0, half) } -private[collection] class IntIndexedSeqStepper[CC <: collection.IndexedSeqOps[Int, AnyConstr, _]](underlying: CC, _i0: Int, _iN: Int) +private[collection] class IntIndexedSeqStepper[CC <: collection.IndexedSeqOps[Int, AnyConstr, ?]](underlying: CC, _i0: Int, _iN: Int) extends IndexedStepperBase[IntStepper, IntIndexedSeqStepper[CC]](_i0, _iN) with IntStepper { def nextStep(): Int = if (hasStep) { val j = i0; i0 += 1; underlying(j) } else Stepper.throwNSEE() protected def semiclone(half: Int): IntIndexedSeqStepper[CC] = new IntIndexedSeqStepper[CC](underlying, i0, half) } -private[collection] class LongIndexedSeqStepper[CC <: collection.IndexedSeqOps[Long, AnyConstr, _]](underlying: CC, _i0: Int, _iN: Int) +private[collection] class LongIndexedSeqStepper[CC <: collection.IndexedSeqOps[Long, AnyConstr, ?]](underlying: CC, _i0: Int, _iN: Int) extends IndexedStepperBase[LongStepper, LongIndexedSeqStepper[CC]](_i0, _iN) with LongStepper { def nextStep(): Long = if (hasStep) { val j = i0; i0 += 1; underlying(j) } else Stepper.throwNSEE() diff --git a/library/src/scala/collection/convert/impl/TableStepper.scala b/library/src/scala/collection/convert/impl/TableStepper.scala index acdd1c57ec64..a79fbfd4968a 100644 --- a/library/src/scala/collection/convert/impl/TableStepper.scala +++ b/library/src/scala/collection/convert/impl/TableStepper.scala @@ -17,7 +17,7 @@ import scala.language.`2.13` import scala.collection.Stepper.EfficientSplit import scala.collection._ -private[collection] abstract class TableStepperBase[A, I <: AnyRef, Sub, Semi <: Sub with TableStepperBase[A, I, _, _]]( +private[collection] abstract class TableStepperBase[A, I <: AnyRef, Sub, Semi <: Sub & TableStepperBase[A, I, ?, ?]]( protected var maxLength: Int, protected val table: Array[I | Null], protected var i0: Int, protected val iN: Int ) extends EfficientSplit { diff --git a/library/src/scala/collection/convert/impl/VectorStepper.scala b/library/src/scala/collection/convert/impl/VectorStepper.scala index 750b3cd55e97..96a12000a8b4 100644 --- a/library/src/scala/collection/convert/impl/VectorStepper.scala +++ b/library/src/scala/collection/convert/impl/VectorStepper.scala @@ -24,9 +24,9 @@ private[convert] abstract class VectorStepperBase[Sub, Semi <: Sub]( ) extends IndexedStepperBase[Sub, Semi](_i0, _iN) { protected var index: Int = 32 // Force an advanceData on the first element - protected var leaves: Array[AnyRef] = _ + protected var leaves: Array[AnyRef] = compiletime.uninitialized protected var index1: Int = 32 // Force advanceData to defer to initTo on the first element - protected var twigs: Array[AnyRef] = _ + protected var twigs: Array[AnyRef] = compiletime.uninitialized protected final def advanceData(iX: Int): Unit = { index1 += 1 diff --git a/library/src/scala/collection/generic/DefaultSerializationProxy.scala b/library/src/scala/collection/generic/DefaultSerializationProxy.scala index d6b5e4e47693..3481241e6ccf 100644 --- a/library/src/scala/collection/generic/DefaultSerializationProxy.scala +++ b/library/src/scala/collection/generic/DefaultSerializationProxy.scala @@ -28,11 +28,11 @@ import scala.collection.mutable.Builder * additional state required to create the proper `Builder` needs to be captured by the `factory`. */ @SerialVersionUID(3L) -final class DefaultSerializationProxy[A](factory: Factory[A, Any], @transient private[this] val coll: Iterable[A]^) extends Serializable { +final class DefaultSerializationProxy[A](factory: Factory[A, Any], @transient private val coll: Iterable[A]^) extends Serializable { - @transient protected var builder: Builder[A, Any] = _ + @transient protected var builder: Builder[A, Any] = compiletime.uninitialized - private[this] def writeObject(out: ObjectOutputStream): Unit = { + private def writeObject(out: ObjectOutputStream): Unit = { out.defaultWriteObject() val k = coll.knownSize out.writeInt(k) @@ -46,7 +46,7 @@ final class DefaultSerializationProxy[A](factory: Factory[A, Any], @transient pr } else out.writeObject(SerializeEnd) } - private[this] def readObject(in: ObjectInputStream): Unit = { + private def readObject(in: ObjectInputStream): Unit = { in.defaultReadObject() builder = factory.newBuilder val k = in.readInt() @@ -65,7 +65,7 @@ final class DefaultSerializationProxy[A](factory: Factory[A, Any], @transient pr } } - protected[this] def readResolve(): Any = builder.result() + protected def readResolve(): Any = builder.result() } @SerialVersionUID(3L) @@ -77,8 +77,8 @@ private[collection] case object SerializeEnd * it directly without using this trait if you need a non-standard factory or if you want to use a different * serialization scheme. */ -transparent trait DefaultSerializable extends Serializable { this: scala.collection.Iterable[_]^ => - protected[this] def writeReplace(): AnyRef^{this} = { +transparent trait DefaultSerializable extends Serializable { this: scala.collection.Iterable[?]^ => + protected def writeReplace(): AnyRef^{this} = { val f: Factory[Any, Any] = this match { case it: scala.collection.SortedMap[_, _] => it.sortedMapFactory.sortedMapFactory[Any, Any](using it.ordering.asInstanceOf[Ordering[Any]]).asInstanceOf[Factory[Any, Any]] case it: scala.collection.Map[_, _] => it.mapFactory.mapFactory[Any, Any].asInstanceOf[Factory[Any, Any]] diff --git a/library/src/scala/collection/generic/IsIterable.scala b/library/src/scala/collection/generic/IsIterable.scala index 4ba72ff3fe08..2e5c7999fd92 100644 --- a/library/src/scala/collection/generic/IsIterable.scala +++ b/library/src/scala/collection/generic/IsIterable.scala @@ -145,7 +145,7 @@ object IsIterable extends IsIterableLowPriority { // The `BitSet` type can not be unified with the `CC0` parameter of // the above definition because it does not take a type parameter. // Hence the need for a separate case: - implicit def bitSetOpsIsIterable[C0 <: BitSet with BitSetOps[C0]]: IsIterable[C0] { type A = Int; type C = C0 } = + implicit def bitSetOpsIsIterable[C0 <: BitSet & BitSetOps[C0]]: IsIterable[C0] { type A = Int; type C = C0 } = new IsIterable[C0] { type A = Int type C = C0 diff --git a/library/src/scala/collection/generic/IsSeq.scala b/library/src/scala/collection/generic/IsSeq.scala index 3e5b644a7ea1..06341db26fb6 100644 --- a/library/src/scala/collection/generic/IsSeq.scala +++ b/library/src/scala/collection/generic/IsSeq.scala @@ -72,11 +72,11 @@ object IsSeq { def length: Int = s.length def apply(i: Int): Char = s.charAt(i) def toIterable: Iterable[Char] = new immutable.WrappedString(s) - protected[this] def coll: String = s - protected[this] def fromSpecific(coll: IterableOnce[Char]^): String = coll.iterator.mkString + protected def coll: String = s + protected def fromSpecific(coll: IterableOnce[Char]^): String = coll.iterator.mkString def iterableFactory: IterableFactory[immutable.ArraySeq] = immutable.ArraySeq.untagged override def empty: String = "" - protected[this] def newSpecificBuilder: mutable.Builder[Char, String] = new StringBuilder + protected def newSpecificBuilder: mutable.Builder[Char, String] = new StringBuilder def iterator: Iterator[Char] = s.iterator } } diff --git a/library/src/scala/collection/immutable/ArraySeq.scala b/library/src/scala/collection/immutable/ArraySeq.scala index 28eeed3c2fa1..e657cf8eda71 100644 --- a/library/src/scala/collection/immutable/ArraySeq.scala +++ b/library/src/scala/collection/immutable/ArraySeq.scala @@ -46,7 +46,7 @@ sealed abstract class ArraySeq[+A] /** The tag of the element type. This does not have to be equal to the element type of this ArraySeq. A primitive * ArraySeq can be backed by an array of boxed values and a reference ArraySeq can be backed by an array of a supertype * or subtype of the element type. */ - protected def elemTag: ClassTag[_] + protected def elemTag: ClassTag[?] override def iterableFactory: SeqFactory[ArraySeq] = ArraySeq.untagged @@ -54,12 +54,12 @@ sealed abstract class ArraySeq[+A] * the expected immutability. Its element type does not have to be equal to the element type of this ArraySeq. * A primitive ArraySeq can be backed by an array of boxed values and a reference ArraySeq can be backed by an * array of a supertype or subtype of the element type. */ - def unsafeArray: Array[_] + def unsafeArray: Array[?] protected def evidenceIterableFactory: ArraySeq.type = ArraySeq protected def iterableEvidence: ClassTag[A @uncheckedVariance] = elemTag.asInstanceOf[ClassTag[A]] - def stepper[S <: Stepper[_]](implicit shape: StepperShape[A, S]): S with EfficientSplit + def stepper[S <: Stepper[?]](implicit shape: StepperShape[A, S]): S & EfficientSplit @throws[ArrayIndexOutOfBoundsException] def apply(i: Int): A @@ -246,7 +246,7 @@ sealed abstract class ArraySeq[+A] override def reverse: ArraySeq[A] = ArraySeq.unsafeWrapArray(new ArrayOps(unsafeArray).reverse).asInstanceOf[ArraySeq[A]] - override protected[this] def className = "ArraySeq" + override protected def className = "ArraySeq" override def copyToArray[B >: A](xs: Array[B], start: Int, len: Int): Int = { val copied = IterableOnce.elemsToCopyToArray(length, xs.length, start, len) @@ -261,7 +261,7 @@ sealed abstract class ArraySeq[+A] override def sorted[B >: A](implicit ord: Ordering[B]): ArraySeq[A] = if(unsafeArray.length <= 1) this else { - val a = Array.copyAs[AnyRef](unsafeArray, length)(ClassTag.AnyRef) + val a = Array.copyAs[AnyRef](unsafeArray, length) Arrays.sort(a, ord.asInstanceOf[Ordering[AnyRef]]) new ArraySeq.ofRef[AnyRef](a).asInstanceOf[ArraySeq[A]] } @@ -276,7 +276,7 @@ sealed abstract class ArraySeq[+A] object ArraySeq extends StrictOptimizedClassTagSeqFactory[ArraySeq] { self => val untagged: SeqFactory[ArraySeq] = new ClassTagSeqFactory.AnySeqDelegate(self) - private[this] lazy val emptyImpl = new ArraySeq.ofRef[Nothing](new Array[Nothing](0)) + private lazy val emptyImpl = new ArraySeq.ofRef[Nothing](new Array[Nothing](0)) def empty[A : ClassTag]: ArraySeq[A] = emptyImpl @@ -349,11 +349,11 @@ object ArraySeq extends StrictOptimizedClassTagSeqFactory[ArraySeq] { self => } } override def iterator: Iterator[T] = new ArrayOps.ArrayIterator[T](unsafeArray) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[T, S]): S with EfficientSplit = ( + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[T, S]): S & EfficientSplit = ( if(shape.shape == StepperShape.ReferenceShape) new ObjectArrayStepper(unsafeArray, 0, unsafeArray.length) - else shape.parUnbox(new ObjectArrayStepper(unsafeArray, 0, unsafeArray.length).asInstanceOf[AnyStepper[T] with EfficientSplit]) - ).asInstanceOf[S with EfficientSplit] + else shape.parUnbox(new ObjectArrayStepper(unsafeArray, 0, unsafeArray.length).asInstanceOf[AnyStepper[T] & EfficientSplit]) + ).asInstanceOf[S & EfficientSplit] } @SerialVersionUID(3L) @@ -376,11 +376,11 @@ object ArraySeq extends StrictOptimizedClassTagSeqFactory[ArraySeq] { self => new ArraySeq.ofByte(a) } else super.sorted[B] override def iterator: Iterator[Byte] = new ArrayOps.ArrayIterator[Byte](unsafeArray) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[Byte, S]): S with EfficientSplit = ( + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[Byte, S]): S & EfficientSplit = ( if(shape.shape == StepperShape.ReferenceShape) AnyStepper.ofParIntStepper(new WidenedByteArrayStepper(unsafeArray, 0, unsafeArray.length)) else new WidenedByteArrayStepper(unsafeArray, 0, unsafeArray.length) - ).asInstanceOf[S with EfficientSplit] + ).asInstanceOf[S & EfficientSplit] override def updated[B >: Byte](index: Int, elem: B): ArraySeq[B] = elem match { case b: Byte => new ArraySeq.ofByte(unsafeArray.updated(index, b)) @@ -418,11 +418,11 @@ object ArraySeq extends StrictOptimizedClassTagSeqFactory[ArraySeq] { self => new ArraySeq.ofShort(a) } else super.sorted[B] override def iterator: Iterator[Short] = new ArrayOps.ArrayIterator[Short](unsafeArray) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[Short, S]): S with EfficientSplit = ( + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[Short, S]): S & EfficientSplit = ( if(shape.shape == StepperShape.ReferenceShape) AnyStepper.ofParIntStepper(new WidenedShortArrayStepper(unsafeArray, 0, unsafeArray.length)) else new WidenedShortArrayStepper(unsafeArray, 0, unsafeArray.length) - ).asInstanceOf[S with EfficientSplit] + ).asInstanceOf[S & EfficientSplit] override def updated[B >: Short](index: Int, elem: B): ArraySeq[B] = elem match { case b: Short => new ArraySeq.ofShort(unsafeArray.updated(index, b)) @@ -460,11 +460,11 @@ object ArraySeq extends StrictOptimizedClassTagSeqFactory[ArraySeq] { self => new ArraySeq.ofChar(a) } else super.sorted[B] override def iterator: Iterator[Char] = new ArrayOps.ArrayIterator[Char](unsafeArray) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[Char, S]): S with EfficientSplit = ( + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[Char, S]): S & EfficientSplit = ( if(shape.shape == StepperShape.ReferenceShape) AnyStepper.ofParIntStepper(new WidenedCharArrayStepper(unsafeArray, 0, unsafeArray.length)) else new WidenedCharArrayStepper(unsafeArray, 0, unsafeArray.length) - ).asInstanceOf[S with EfficientSplit] + ).asInstanceOf[S & EfficientSplit] override def updated[B >: Char](index: Int, elem: B): ArraySeq[B] = elem match { case b: Char => new ArraySeq.ofChar(unsafeArray.updated(index, b)) @@ -505,11 +505,11 @@ object ArraySeq extends StrictOptimizedClassTagSeqFactory[ArraySeq] { self => new ArraySeq.ofInt(a) } else super.sorted[B] override def iterator: Iterator[Int] = new ArrayOps.ArrayIterator[Int](unsafeArray) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[Int, S]): S with EfficientSplit = ( + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[Int, S]): S & EfficientSplit = ( if(shape.shape == StepperShape.ReferenceShape) AnyStepper.ofParIntStepper(new IntArrayStepper(unsafeArray, 0, unsafeArray.length)) else new IntArrayStepper(unsafeArray, 0, unsafeArray.length) - ).asInstanceOf[S with EfficientSplit] + ).asInstanceOf[S & EfficientSplit] override def updated[B >: Int](index: Int, elem: B): ArraySeq[B] = elem match { case b: Int => new ArraySeq.ofInt(unsafeArray.updated(index, b)) @@ -547,11 +547,11 @@ object ArraySeq extends StrictOptimizedClassTagSeqFactory[ArraySeq] { self => new ArraySeq.ofLong(a) } else super.sorted[B] override def iterator: Iterator[Long] = new ArrayOps.ArrayIterator[Long](unsafeArray) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[Long, S]): S with EfficientSplit = ( + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[Long, S]): S & EfficientSplit = ( if(shape.shape == StepperShape.ReferenceShape) AnyStepper.ofParLongStepper(new LongArrayStepper(unsafeArray, 0, unsafeArray.length)) else new LongArrayStepper(unsafeArray, 0, unsafeArray.length) - ).asInstanceOf[S with EfficientSplit] + ).asInstanceOf[S & EfficientSplit] override def updated[B >: Long](index: Int, elem: B): ArraySeq[B] = elem match { case b: Long => new ArraySeq.ofLong(unsafeArray.updated(index, b)) @@ -589,11 +589,11 @@ object ArraySeq extends StrictOptimizedClassTagSeqFactory[ArraySeq] { self => case _ => super.equals(that) } override def iterator: Iterator[Float] = new ArrayOps.ArrayIterator[Float](unsafeArray) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[Float, S]): S with EfficientSplit = ( + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[Float, S]): S & EfficientSplit = ( if(shape.shape == StepperShape.ReferenceShape) AnyStepper.ofParDoubleStepper(new WidenedFloatArrayStepper(unsafeArray, 0, unsafeArray.length)) else new WidenedFloatArrayStepper(unsafeArray, 0, unsafeArray.length) - ).asInstanceOf[S with EfficientSplit] + ).asInstanceOf[S & EfficientSplit] override def updated[B >: Float](index: Int, elem: B): ArraySeq[B] = elem match { case b: Float => new ArraySeq.ofFloat(unsafeArray.updated(index, b)) @@ -631,11 +631,11 @@ object ArraySeq extends StrictOptimizedClassTagSeqFactory[ArraySeq] { self => case _ => super.equals(that) } override def iterator: Iterator[Double] = new ArrayOps.ArrayIterator[Double](unsafeArray) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[Double, S]): S with EfficientSplit = ( + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[Double, S]): S & EfficientSplit = ( if(shape.shape == StepperShape.ReferenceShape) AnyStepper.ofParDoubleStepper(new DoubleArrayStepper(unsafeArray, 0, unsafeArray.length)) else new DoubleArrayStepper(unsafeArray, 0, unsafeArray.length) - ).asInstanceOf[S with EfficientSplit] + ).asInstanceOf[S & EfficientSplit] override def updated[B >: Double](index: Int, elem: B): ArraySeq[B] = elem match { case b: Double => new ArraySeq.ofDouble(unsafeArray.updated(index, b)) @@ -673,8 +673,8 @@ object ArraySeq extends StrictOptimizedClassTagSeqFactory[ArraySeq] { self => new ArraySeq.ofBoolean(a) } else super.sorted[B] override def iterator: Iterator[Boolean] = new ArrayOps.ArrayIterator[Boolean](unsafeArray) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[Boolean, S]): S with EfficientSplit = - new BoxedBooleanArrayStepper(unsafeArray, 0, unsafeArray.length).asInstanceOf[S with EfficientSplit] + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[Boolean, S]): S & EfficientSplit = + new BoxedBooleanArrayStepper(unsafeArray, 0, unsafeArray.length).asInstanceOf[S & EfficientSplit] override def updated[B >: Boolean](index: Int, elem: B): ArraySeq[B] = elem match { case b: Boolean => new ArraySeq.ofBoolean(unsafeArray.updated(index, b)) @@ -705,7 +705,7 @@ object ArraySeq extends StrictOptimizedClassTagSeqFactory[ArraySeq] { self => case _ => super.equals(that) } override def iterator: Iterator[Unit] = new ArrayOps.ArrayIterator[Unit](unsafeArray) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[Unit, S]): S with EfficientSplit = - new ObjectArrayStepper[AnyRef](unsafeArray.asInstanceOf[Array[AnyRef]], 0, unsafeArray.length).asInstanceOf[S with EfficientSplit] + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[Unit, S]): S & EfficientSplit = + new ObjectArrayStepper[AnyRef](unsafeArray.asInstanceOf[Array[AnyRef]], 0, unsafeArray.length).asInstanceOf[S & EfficientSplit] } } diff --git a/library/src/scala/collection/immutable/BitSet.scala b/library/src/scala/collection/immutable/BitSet.scala index 176c31794621..bf76c4c66344 100644 --- a/library/src/scala/collection/immutable/BitSet.scala +++ b/library/src/scala/collection/immutable/BitSet.scala @@ -85,7 +85,7 @@ sealed abstract class BitSet override def zip[B](that: scala.IterableOnce[B]^)(implicit @implicitNotFound(collection.BitSet.zipOrdMsg) ev: Ordering[(Int, B)]): SortedSet[(Int, B)] = super.zip(that) - protected[this] def writeReplace(): AnyRef = new BitSet.SerializationProxy(this) + protected def writeReplace(): AnyRef = new BitSet.SerializationProxy(this) } /** @@ -373,6 +373,6 @@ object BitSet extends SpecificIterableFactory[Int, BitSet] { @SerialVersionUID(3L) private final class SerializationProxy(coll: BitSet) extends scala.collection.BitSet.SerializationProxy(coll) { - protected[this] def readResolve(): Any = BitSet.fromBitMaskNoCopy(elems) + protected def readResolve(): Any = BitSet.fromBitMaskNoCopy(elems) } } diff --git a/library/src/scala/collection/immutable/ChampCommon.scala b/library/src/scala/collection/immutable/ChampCommon.scala index 86b212de72f9..de3941510058 100644 --- a/library/src/scala/collection/immutable/ChampCommon.scala +++ b/library/src/scala/collection/immutable/ChampCommon.scala @@ -59,7 +59,7 @@ private[collection] abstract class Node[T <: Node[T]] { def cachedJavaKeySetHashCode: Int - private final def arrayIndexOutOfBounds(as: Array[_], ix:Int): ArrayIndexOutOfBoundsException = + private final def arrayIndexOutOfBounds(as: Array[?], ix:Int): ArrayIndexOutOfBoundsException = new ArrayIndexOutOfBoundsException(s"$ix is out of bounds (min 0, max ${as.length-1}") protected final def removeElement(as: Array[Int], ix: Int): Array[Int] = { @@ -118,11 +118,11 @@ private[immutable] abstract class ChampBaseIterator[A, T <: Node[T]] extends Abs protected var currentValueCursor: Int = 0 protected var currentValueLength: Int = 0 - protected var currentValueNode: T = _ + protected var currentValueNode: T = compiletime.uninitialized - private[this] var currentStackLevel: Int = -1 - private[this] var nodeCursorsAndLengths: Array[Int] = _ - private[this] var nodes: Array[T] = _ + private var currentStackLevel: Int = -1 + private var nodeCursorsAndLengths: Array[Int] = compiletime.uninitialized + private var nodes: Array[T] = compiletime.uninitialized private def initNodes(): Unit = { if (nodeCursorsAndLengths eq null) { nodeCursorsAndLengths = new Array[Int](MaxDepth * 2) @@ -200,11 +200,11 @@ private[immutable] abstract class ChampBaseReverseIterator[A, T <: Node[T]] exte import Node.MaxDepth protected var currentValueCursor: Int = -1 - protected var currentValueNode: T = _ + protected var currentValueNode: T = compiletime.uninitialized - private[this] var currentStackLevel: Int = -1 - private[this] val nodeIndex: Array[Int] = new Array[Int](MaxDepth + 1) - private[this] val nodeStack: Array[T] = new Array[Node[T]](MaxDepth + 1).asInstanceOf[Array[T]] + private var currentStackLevel: Int = -1 + private val nodeIndex: Array[Int] = new Array[Int](MaxDepth + 1) + private val nodeStack: Array[T] = new Array[Node[T]](MaxDepth + 1).asInstanceOf[Array[T]] def this(rootNode: T) = { this() diff --git a/library/src/scala/collection/immutable/HashMap.scala b/library/src/scala/collection/immutable/HashMap.scala index 2a4774a75c3c..f2d7b4bb45e7 100644 --- a/library/src/scala/collection/immutable/HashMap.scala +++ b/library/src/scala/collection/immutable/HashMap.scala @@ -62,9 +62,9 @@ final class HashMap[K, +V] private[immutable] (private[immutable] val rootNode: private[immutable] final class HashKeySet extends ImmutableKeySet { - private[this] def newKeySetOrThis(newHashMap: HashMap[K, _]): Set[K] = + private def newKeySetOrThis(newHashMap: HashMap[K, ?]): Set[K] = if (newHashMap eq HashMap.this) this else newHashMap.keySet - private[this] def newKeySetOrThis(newRootNode: BitmapIndexedMapNode[K, _]): Set[K] = + private def newKeySetOrThis(newRootNode: BitmapIndexedMapNode[K, ?]): Set[K] = if (newRootNode eq rootNode) this else new HashMap(newRootNode).keySet override def incl(elem: K): Set[K] = { @@ -97,11 +97,11 @@ final class HashMap[K, +V] private[immutable] (private[immutable] val rootNode: else new MapKeyValueTupleReverseIterator[K, V](rootNode) } - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[(K, V), S]): S with EfficientSplit = + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[(K, V), S]): S & EfficientSplit = shape. parUnbox(collection.convert.impl.AnyChampStepper.from[(K, V), MapNode[K, V]](size, rootNode, (node, i) => node.getPayload(i))) - override def keyStepper[S <: Stepper[_]](implicit shape: StepperShape[K, S]): S with EfficientSplit = { + override def keyStepper[S <: Stepper[?]](implicit shape: StepperShape[K, S]): S & EfficientSplit = { import collection.convert.impl._ val s = shape.shape match { case StepperShape.IntShape => IntChampStepper.from[ MapNode[K, V]](size, rootNode, (node, i) => node.getKey(i).asInstanceOf[Int]) @@ -109,10 +109,10 @@ final class HashMap[K, +V] private[immutable] (private[immutable] val rootNode: case StepperShape.DoubleShape => DoubleChampStepper.from[MapNode[K, V]](size, rootNode, (node, i) => node.getKey(i).asInstanceOf[Double]) case _ => shape.parUnbox(AnyChampStepper.from[K, MapNode[K, V]](size, rootNode, (node, i) => node.getKey(i))) } - s.asInstanceOf[S with EfficientSplit] + s.asInstanceOf[S & EfficientSplit] } - override def valueStepper[S <: Stepper[_]](implicit shape: StepperShape[V, S]): S with EfficientSplit = { + override def valueStepper[S <: Stepper[?]](implicit shape: StepperShape[V, S]): S & EfficientSplit = { import collection.convert.impl._ val s = shape.shape match { case StepperShape.IntShape => IntChampStepper.from[ MapNode[K, V]](size, rootNode, (node, i) => node.getValue(i).asInstanceOf[Int]) @@ -120,7 +120,7 @@ final class HashMap[K, +V] private[immutable] (private[immutable] val rootNode: case StepperShape.DoubleShape => DoubleChampStepper.from[MapNode[K, V]](size, rootNode, (node, i) => node.getValue(i).asInstanceOf[Double]) case _ => shape.parUnbox(AnyChampStepper.from[V, MapNode[K, V]](size, rootNode, (node, i) => node.getValue(i))) } - s.asInstanceOf[S with EfficientSplit] + s.asInstanceOf[S & EfficientSplit] } override final def contains(key: K): Boolean = { @@ -147,7 +147,7 @@ final class HashMap[K, +V] private[immutable] (private[immutable] val rootNode: rootNode.getOrElse(key, keyUnimprovedHash, keyHash, 0, default) } - @inline private[this] def newHashMapOrThis[V1 >: V](newRootNode: BitmapIndexedMapNode[K, V1]): HashMap[K, V1] = + @inline private def newHashMapOrThis[V1 >: V](newRootNode: BitmapIndexedMapNode[K, V1]): HashMap[K, V1] = if (newRootNode eq rootNode) this else new HashMap(newRootNode) def updated[V1 >: V](key: K, value: V1): HashMap[K, V1] = { @@ -294,7 +294,7 @@ final class HashMap[K, +V] private[immutable] (private[immutable] val rootNode: } } - override protected[this] def className = "HashMap" + override protected def className = "HashMap" /** Merges this HashMap with an other HashMap by combining all key-value pairs of both maps, and delegating to a merge * function to resolve any key collisions between the two HashMaps. @@ -2157,8 +2157,8 @@ private final class MapKeyValueTupleReverseIterator[K, V](rootNode: MapNode[K, V private final class MapKeyValueTupleHashIterator[K, V](rootNode: MapNode[K, V]) extends ChampBaseReverseIterator[Any, MapNode[K, V]](rootNode) { - private[this] var hash = 0 - private[this] var value: V = _ + private var hash = 0 + private var value: V = compiletime.uninitialized override def hashCode(): Int = MurmurHash3.tuple2Hash(hash, value.##, MurmurHash3.productSeed) def next(): MapKeyValueTupleHashIterator[K, V] = { if (!hasNext) Iterator.empty.next() @@ -2232,7 +2232,7 @@ private[immutable] final class HashMapBuilder[K, V] extends ReusableBuilder[(K, * Indicates that on next add, the elements should be copied to an identical structure, before continuing * mutations. */ @annotation.stableNull - private var aliased: HashMap[K, V] | Null = _ + private var aliased: HashMap[K, V] | Null = compiletime.uninitialized private def isAliased: Boolean = aliased != null @@ -2247,7 +2247,7 @@ private[immutable] final class HashMapBuilder[K, V] extends ReusableBuilder[(K, } /** Inserts element `elem` into array `as` at index `ix`, shifting right the trailing elems */ - private[this] def insertElement(as: Array[Int], ix: Int, elem: Int): Array[Int] = { + private def insertElement(as: Array[Int], ix: Int, elem: Int): Array[Int] = { if (ix < 0) throw new ArrayIndexOutOfBoundsException if (ix > as.length) throw new ArrayIndexOutOfBoundsException val result = new Array[Int](as.length + 1) @@ -2258,7 +2258,7 @@ private[immutable] final class HashMapBuilder[K, V] extends ReusableBuilder[(K, } /** Inserts key-value into the bitmapIndexMapNode. Requires that this is a new key-value pair */ - private[this] def insertValue[V1 >: V](bm: BitmapIndexedMapNode[K, V],bitpos: Int, key: K, originalHash: Int, keyHash: Int, value: V1): Unit = { + private def insertValue[V1 >: V](bm: BitmapIndexedMapNode[K, V],bitpos: Int, key: K, originalHash: Int, keyHash: Int, value: V1): Unit = { val dataIx = bm.dataIndex(bitpos) val idx = TupleLength * dataIx @@ -2325,13 +2325,13 @@ private[immutable] final class HashMapBuilder[K, V] extends ReusableBuilder[(K, } /** If currently referencing aliased structure, copy elements to new mutable structure */ - private[this] def ensureUnaliased() = { + private def ensureUnaliased() = { if (isAliased) copyElems() aliased = null } /** Copy elements to new mutable structure */ - private[this] def copyElems(): Unit = { + private def copyElems(): Unit = { rootNode = rootNode.copy() } diff --git a/library/src/scala/collection/immutable/HashSet.scala b/library/src/scala/collection/immutable/HashSet.scala index c052dee5506d..a042f6256c80 100644 --- a/library/src/scala/collection/immutable/HashSet.scala +++ b/library/src/scala/collection/immutable/HashSet.scala @@ -45,7 +45,7 @@ final class HashSet[A] private[immutable](private[immutable] val rootNode: Bitma // This release fence is present because rootNode may have previously been mutated during construction. releaseFence() - private[this] def newHashSetOrThis(newRootNode: BitmapIndexedSetNode[A]): HashSet[A] = + private def newHashSetOrThis(newRootNode: BitmapIndexedSetNode[A]): HashSet[A] = if (rootNode eq newRootNode) this else new HashSet(newRootNode) override def iterableFactory: IterableFactory[HashSet] = HashSet @@ -63,7 +63,7 @@ final class HashSet[A] private[immutable](private[immutable] val rootNode: Bitma protected[immutable] def reverseIterator: Iterator[A] = new SetReverseIterator[A](rootNode) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[A, S]): S with EfficientSplit = { + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[A, S]): S & EfficientSplit = { import convert.impl._ val s = shape.shape match { case StepperShape.IntShape => IntChampStepper.from[ SetNode[A]](size, rootNode, (node, i) => node.getPayload(i).asInstanceOf[Int]) @@ -71,7 +71,7 @@ final class HashSet[A] private[immutable](private[immutable] val rootNode: Bitma case StepperShape.DoubleShape => DoubleChampStepper.from[SetNode[A]](size, rootNode, (node, i) => node.getPayload(i).asInstanceOf[Double]) case _ => shape.parUnbox(AnyChampStepper.from[A, SetNode[A]](size, rootNode, (node, i) => node.getPayload(i))) } - s.asInstanceOf[S with EfficientSplit] + s.asInstanceOf[S & EfficientSplit] } def contains(element: A): Boolean = { @@ -208,7 +208,7 @@ final class HashSet[A] private[immutable](private[immutable] val rootNode: Bitma case _ => super.equals(that) } - override protected[this] def className = "HashSet" + override protected def className = "HashSet" override def hashCode(): Int = { val it = new SetHashIterator(rootNode) @@ -279,7 +279,7 @@ final class HashSet[A] private[immutable](private[immutable] val rootNode: Bitma * * That is, this method is safe to call on published sets because it does not mutate `this` */ - private[this] def removedAllWithShallowMutations(that: IterableOnce[A]^): HashSet[A] = { + private def removedAllWithShallowMutations(that: IterableOnce[A]^): HashSet[A] = { val iter = that.iterator var curr = rootNode while (iter.hasNext) { @@ -1319,7 +1319,7 @@ private final class BitmapIndexedSetNode[A]( * @param newNodes queue in order of child position, of all new nodes to include in the new SetNode * @param newCachedHashCode the cached java keyset hashcode of the new SetNode */ - private[this] def newNodeFrom( + private def newNodeFrom( newSize: Int, newDataMap: Int, newNodeMap: Int, @@ -1910,7 +1910,7 @@ private final class SetReverseIterator[A](rootNode: SetNode[A]) private final class SetHashIterator[A](rootNode: SetNode[A]) extends ChampBaseIterator[AnyRef, SetNode[A]](rootNode) { - private[this] var hash = 0 + private var hash = 0 override def hashCode(): Int = hash def next(): AnyRef = { diff --git a/library/src/scala/collection/immutable/IntMap.scala b/library/src/scala/collection/immutable/IntMap.scala index 6705091640b8..5e508360993c 100644 --- a/library/src/scala/collection/immutable/IntMap.scala +++ b/library/src/scala/collection/immutable/IntMap.scala @@ -91,19 +91,19 @@ object IntMap { implicit def toFactory[V](dummy: IntMap.type): Factory[(Int, V), IntMap[V]] = ToFactory.asInstanceOf[Factory[(Int, V), IntMap[V]]] @SerialVersionUID(3L) - private[this] object ToFactory extends Factory[(Int, AnyRef), IntMap[AnyRef]] with Serializable { + private object ToFactory extends Factory[(Int, AnyRef), IntMap[AnyRef]] with Serializable { def fromSpecific(it: IterableOnce[(Int, AnyRef)]^): IntMap[AnyRef] = IntMap.from[AnyRef](it) def newBuilder: Builder[(Int, AnyRef), IntMap[AnyRef]] = IntMap.newBuilder[AnyRef] } implicit def toBuildFrom[V](factory: IntMap.type): BuildFrom[Any, (Int, V), IntMap[V]] = ToBuildFrom.asInstanceOf[BuildFrom[Any, (Int, V), IntMap[V]]] - private[this] object ToBuildFrom extends BuildFrom[Any, (Int, AnyRef), IntMap[AnyRef]] { + private object ToBuildFrom extends BuildFrom[Any, (Int, AnyRef), IntMap[AnyRef]] { def fromSpecific(from: Any)(it: IterableOnce[(Int, AnyRef)]^) = IntMap.from(it) def newBuilder(from: Any) = IntMap.newBuilder[AnyRef] } implicit def iterableFactory[V]: Factory[(Int, V), IntMap[V]] = toFactory(this) - implicit def buildFromIntMap[V]: BuildFrom[IntMap[_], (Int, V), IntMap[V]] = toBuildFrom(this) + implicit def buildFromIntMap[V]: BuildFrom[IntMap[?], (Int, V), IntMap[V]] = toBuildFrom(this) } // Iterator over a non-empty IntMap. @@ -263,7 +263,7 @@ sealed abstract class IntMap[+T] extends AbstractMap[Int, T] case IntMap.Nil => } - override protected[this] def className = "IntMap" + override protected def className = "IntMap" override def isEmpty = this eq IntMap.Nil override def knownSize: Int = if (isEmpty) 0 else super.knownSize @@ -501,5 +501,5 @@ sealed abstract class IntMap[+T] extends AbstractMap[Int, T] case IntMap.Nil => throw new IllegalStateException("Empty set") } - protected[this] def writeReplace(): AnyRef = new DefaultSerializationProxy(IntMap.toFactory[T](IntMap), this) + protected def writeReplace(): AnyRef = new DefaultSerializationProxy(IntMap.toFactory[T](IntMap), this) } diff --git a/library/src/scala/collection/immutable/LazyList.scala b/library/src/scala/collection/immutable/LazyList.scala index 82c1402999f4..303f228ddbfb 100644 --- a/library/src/scala/collection/immutable/LazyList.scala +++ b/library/src/scala/collection/immutable/LazyList.scala @@ -287,7 +287,7 @@ final class LazyList[+A] private (lazyState: AnyRef /* EmptyMarker.type | () => // after initialization (`_head ne Uninitialized`) // - `null` if this is an empty lazy list // - `head: A` otherwise (can be `null`, `_tail == null` is used to test emptiness) - @volatile private[this] var _head: Any /* Uninitialized | A */ = + @volatile private var _head: Any /* Uninitialized | A */ = if (lazyState eq EmptyMarker) null else Uninitialized // when `_head eq Uninitialized` @@ -296,7 +296,7 @@ final class LazyList[+A] private (lazyState: AnyRef /* EmptyMarker.type | () => // when `_head ne Uninitialized` // - `null` if this is an empty lazy list // - `tail: LazyList[A]` otherwise - private[this] var _tail: AnyRef | Null /* () => LazyList[A] | MidEvaluation.type | LazyList[A] | Null */ = + private var _tail: AnyRef | Null /* () => LazyList[A] | MidEvaluation.type | LazyList[A] | Null */ = if (lazyState eq EmptyMarker) null else lazyState private def rawHead: Any = _head @@ -358,7 +358,7 @@ final class LazyList[+A] private (lazyState: AnyRef /* EmptyMarker.type | () => if (evaluated eq Empty) throw new UnsupportedOperationException("tail of empty lazy list") else rawTail.asInstanceOf[LazyList[A]] - @inline private[this] def knownIsEmpty: Boolean = isEvaluated && isEmpty + @inline private def knownIsEmpty: Boolean = isEvaluated && isEmpty @inline private def knownNonEmpty: Boolean = isEvaluated && !isEmpty /** Evaluates all undefined elements of the lazy list. @@ -439,10 +439,10 @@ final class LazyList[+A] private (lazyState: AnyRef /* EmptyMarker.type | () => else tail.foldLeft(op(z, head))(op) // LazyList.Empty doesn't use the SerializationProxy - protected[this] def writeReplace(): AnyRef = + protected def writeReplace(): AnyRef = if (knownNonEmpty) new SerializationProxy[A](this) else this - override protected[this] def className = "LazyList" + override protected def className = "LazyList" /** The lazy list resulting from the concatenation of this lazy list with the argument lazy list. * @@ -532,7 +532,7 @@ final class LazyList[+A] private (lazyState: AnyRef /* EmptyMarker.type | () => */ override def partitionMap[A1, A2](f: A => Either[A1, A2]): (LazyList[A1], LazyList[A2]) = { val (left, right) = map(f).partition(_.isLeft) - (left.map(_.asInstanceOf[Left[A1, _]].value), right.map(_.asInstanceOf[Right[_, A2]].value)) + (left.map(_.asInstanceOf[Left[A1, ?]].value), right.map(_.asInstanceOf[Right[?, A2]].value)) } /** @inheritdoc @@ -755,7 +755,7 @@ final class LazyList[+A] private (lazyState: AnyRef /* EmptyMarker.type | () => } } - private def eagerHeadDropRightImpl(scout: LazyList[_]): LazyList[A] = + private def eagerHeadDropRightImpl(scout: LazyList[?]): LazyList[A] = if (scout.isEmpty) Empty else eagerCons(head, newLL(tail.eagerHeadDropRightImpl(scout.tail))) @@ -931,7 +931,7 @@ final class LazyList[+A] private (lazyState: AnyRef /* EmptyMarker.type | () => sb } - private[this] def addStringNoForce(b: JStringBuilder, start: String, sep: String, end: String): b.type = { + private def addStringNoForce(b: JStringBuilder, start: String, sep: String, end: String): b.type = { b.append(start) if (!isEvaluated) b.append("") else if (!isEmpty) { @@ -1316,7 +1316,7 @@ object LazyList extends SeqFactory[LazyList] { */ def newBuilder[A]: Builder[A, LazyList[A]] = new LazyBuilder[A] - private class LazyIterator[+A](private[this] var lazyList: LazyList[A]) extends AbstractIterator[A] { + private class LazyIterator[+A](private var lazyList: LazyList[A]) extends AbstractIterator[A] { override def hasNext: Boolean = !lazyList.isEmpty override def next(): A = @@ -1328,7 +1328,7 @@ object LazyList extends SeqFactory[LazyList] { } } - private class SlidingIterator[A](private[this] var lazyList: LazyList[A], size: Int, step: Int) + private class SlidingIterator[A](private var lazyList: LazyList[A], size: Int, step: Int) extends AbstractIterator[LazyList[A]] { private val minLen = size - step max 0 private var first = true @@ -1350,7 +1350,7 @@ object LazyList extends SeqFactory[LazyList] { private final class WithFilter[A] private[LazyList](lazyList: LazyList[A], p: A => Boolean) extends collection.WithFilter[A, LazyList] { - private[this] val filtered = lazyList.filter(p) + private val filtered = lazyList.filter(p) def map[B](f: A => B): LazyList[B] = filtered.map(f) def flatMap[B](f: A => IterableOnce[B]): LazyList[B] = filtered.flatMap(f) def foreach[U](f: A => U): Unit = filtered.foreach(f) @@ -1360,8 +1360,8 @@ object LazyList extends SeqFactory[LazyList] { private final class LazyBuilder[A] extends ReusableBuilder[A, LazyList[A]] { import LazyBuilder._ - private[this] var next: DeferredState[A] = _ - private[this] var list: LazyList[A] = _ + private var next: DeferredState[A] = compiletime.uninitialized + private var list: LazyList[A] = compiletime.uninitialized clear() @@ -1396,7 +1396,7 @@ object LazyList extends SeqFactory[LazyList] { private object LazyBuilder { final class DeferredState[A] { - private[this] var _tail: () => LazyList[A] = _ + private var _tail: () => LazyList[A] = compiletime.uninitialized def eval(): LazyList[A] = { val state = _tail @@ -1420,7 +1420,7 @@ object LazyList extends SeqFactory[LazyList] { @SerialVersionUID(4L) final class SerializationProxy[A](@transient protected var coll: LazyList[A]) extends Serializable { - private[this] def writeObject(out: ObjectOutputStream): Unit = { + private def writeObject(out: ObjectOutputStream): Unit = { out.defaultWriteObject() var these = coll while (these.knownNonEmpty) { @@ -1431,7 +1431,7 @@ object LazyList extends SeqFactory[LazyList] { out.writeObject(these) } - private[this] def readObject(in: ObjectInputStream): Unit = { + private def readObject(in: ObjectInputStream): Unit = { in.defaultReadObject() val init = new mutable.ListBuffer[A] var initRead = false @@ -1446,7 +1446,7 @@ object LazyList extends SeqFactory[LazyList] { coll = newLL(eagerHeadPrependIterator(it)(tail)) } - private[this] def readResolve(): Any = coll + private def readResolve(): Any = coll } } diff --git a/library/src/scala/collection/immutable/LazyListIterable.scala b/library/src/scala/collection/immutable/LazyListIterable.scala index 9c1fa127addf..dd0ec12a14f6 100644 --- a/library/src/scala/collection/immutable/LazyListIterable.scala +++ b/library/src/scala/collection/immutable/LazyListIterable.scala @@ -286,7 +286,7 @@ final class LazyListIterable[+A] private (lazyState: LazyListIterable.EmptyMarke // after initialization (`_head ne Uninitialized`) // - `null` if this is an empty lazy list // - `head: A` otherwise (can be `null`, `_tail == null` is used to test emptiness) - @volatile private[this] var _head: Any /* Uninitialized | A */ = + @volatile private var _head: Any /* Uninitialized | A */ = if (lazyState eq EmptyMarker) null else Uninitialized // when `_head eq Uninitialized` @@ -295,7 +295,7 @@ final class LazyListIterable[+A] private (lazyState: LazyListIterable.EmptyMarke // when `_head ne Uninitialized` // - `null` if this is an empty lazy list // - `tail: LazyListIterable[A]` otherwise - private[this] var _tail: AnyRef^{this} | Null /* () => LazyListIterable[A] | MidEvaluation.type | LazyListIterable[A] | Null */ = + private var _tail: AnyRef^{this} | Null /* () => LazyListIterable[A] | MidEvaluation.type | LazyListIterable[A] | Null */ = if (lazyState eq EmptyMarker) null else lazyState private def rawHead: Any = _head @@ -379,7 +379,7 @@ final class LazyListIterable[+A] private (lazyState: LazyListIterable.EmptyMarke skipped.head } - @inline private[this] def knownIsEmpty: Boolean = isEvaluated && isEmpty + @inline private def knownIsEmpty: Boolean = isEvaluated && isEmpty @inline private def knownNonEmpty: Boolean = isEvaluated && !isEmpty /** Evaluates all undefined elements of the lazy list. @@ -460,10 +460,10 @@ final class LazyListIterable[+A] private (lazyState: LazyListIterable.EmptyMarke else tail.foldLeft(op(z, head))(op) // LazyListIterable.Empty doesn't use the SerializationProxy - protected[this] def writeReplace(): AnyRef^{this} = + protected def writeReplace(): AnyRef^{this} = if (knownNonEmpty) new SerializationProxy[A](this) else this - override protected[this] def className = "LazyListIterable" + override protected def className = "LazyListIterable" /** The lazy list resulting from the concatenation of this lazy list with the argument lazy list. * @@ -553,7 +553,7 @@ final class LazyListIterable[+A] private (lazyState: LazyListIterable.EmptyMarke */ override def partitionMap[A1, A2](f: A => Either[A1, A2]): (LazyListIterable[A1]^{this, f}, LazyListIterable[A2]^{this, f}) = { val p: (LazyListIterable[Either[A1, A2]]^{this, f}, LazyListIterable[Either[A1, A2]]^{this, f}) = map(f).partition(_.isLeft) - (p._1.map(_.asInstanceOf[Left[A1, _]].value), p._2.map(_.asInstanceOf[Right[_, A2]].value)) + (p._1.map(_.asInstanceOf[Left[A1, ?]].value), p._2.map(_.asInstanceOf[Right[?, A2]].value)) } /** @inheritdoc @@ -776,7 +776,7 @@ final class LazyListIterable[+A] private (lazyState: LazyListIterable.EmptyMarke } } - private def eagerHeadDropRightImpl(scout: LazyListIterable[_]^): LazyListIterable[A]^{this, scout} = + private def eagerHeadDropRightImpl(scout: LazyListIterable[?]^): LazyListIterable[A]^{this, scout} = if (scout.isEmpty) Empty else eagerCons(head, newLL(tail.eagerHeadDropRightImpl(scout.tail))) @@ -954,7 +954,7 @@ final class LazyListIterable[+A] private (lazyState: LazyListIterable.EmptyMarke sb } - private[this] def addStringNoForce(b: JStringBuilder, start: String, sep: String, end: String): b.type = { + private def addStringNoForce(b: JStringBuilder, start: String, sep: String, end: String): b.type = { b.append(start) if (!isEvaluated) b.append("") else if (!isEmpty) { @@ -1340,7 +1340,7 @@ object LazyListIterable extends IterableFactory[LazyListIterable] { */ def newBuilder[A]: Builder[A, LazyListIterable[A]] = (new collection.mutable.ListBuffer[A]).mapResult(from) - private class LazyIterator[+A](private[this] var lazyList: LazyListIterable[A]^) extends AbstractIterator[A] { + private class LazyIterator[+A](private var lazyList: LazyListIterable[A]^) extends AbstractIterator[A] { override def hasNext: Boolean = !lazyList.isEmpty override def next(): A = @@ -1354,7 +1354,7 @@ object LazyListIterable extends IterableFactory[LazyListIterable] { private class SlidingIterator[A](l: LazyListIterable[A]^, size: Int, step: Int) extends AbstractIterator[LazyListIterable[A]^{l}] { - private[this] var lazyList: LazyListIterable[A]^{l} = l + private var lazyList: LazyListIterable[A]^{l} = l private val minLen = size - step max 0 private var first = true @@ -1375,7 +1375,7 @@ object LazyListIterable extends IterableFactory[LazyListIterable] { private final class WithFilter[A] private[LazyListIterable](lazyList: LazyListIterable[A]^, p: A => Boolean) extends collection.WithFilter[A, LazyListIterable] { - @untrackedCaptures private[this] val filtered = lazyList.filter(p) + @untrackedCaptures private val filtered = lazyList.filter(p) def map[B](f: A => B): LazyListIterable[B]^{this, f} = filtered.map(f) def flatMap[B](f: A => IterableOnce[B]^): LazyListIterable[B]^{this, f} = filtered.flatMap(f) def foreach[U](f: A => U): Unit = filtered.foreach(f) @@ -1448,7 +1448,7 @@ object LazyListIterable extends IterableFactory[LazyListIterable] { final class SerializationProxy[A](of: LazyListIterable[A]^) extends Serializable { @transient protected var coll: LazyListIterable[A]^{this} = of - private[this] def writeObject(out: ObjectOutputStream): Unit = { + private def writeObject(out: ObjectOutputStream): Unit = { out.defaultWriteObject() var these: LazyListIterable[A]^{this} = coll while (these.knownNonEmpty) { @@ -1459,7 +1459,7 @@ object LazyListIterable extends IterableFactory[LazyListIterable] { out.writeObject(these) } - private[this] def readObject(in: ObjectInputStream): Unit = { + private def readObject(in: ObjectInputStream): Unit = { in.defaultReadObject() val init = new mutable.ListBuffer[A] var initRead = false @@ -1474,6 +1474,6 @@ object LazyListIterable extends IterableFactory[LazyListIterable] { coll = newLL(eagerHeadPrependIterator(it)(tail)) } - private[this] def readResolve(): Any = coll + private def readResolve(): Any = coll } } diff --git a/library/src/scala/collection/immutable/List.scala b/library/src/scala/collection/immutable/List.scala index a26e63078b24..06871192c0d3 100644 --- a/library/src/scala/collection/immutable/List.scala +++ b/library/src/scala/collection/immutable/List.scala @@ -438,7 +438,7 @@ sealed abstract class List[+A] super.corresponds(that)(p) } - override protected[this] def className = "List" + override protected def className = "List" /** Builds a new list by applying a function to all elements of this list. * Like `xs map f`, but returns `xs` unchanged if function @@ -497,7 +497,7 @@ sealed abstract class List[+A] override def filterNot(p: A => Boolean): List[A] = filterCommon(p, isFlipped = true) - private[this] def filterCommon(p: A => Boolean, isFlipped: Boolean): List[A] = { + private def filterCommon(p: A => Boolean, isFlipped: Boolean): List[A] = { // everything seen so far so far is not included @tailrec def noneIn(l: List[A]): List[A] = { @@ -590,7 +590,7 @@ sealed abstract class List[+A] // Override for performance override def equals(o: scala.Any): Boolean = { - @tailrec def listEq(a: List[_], b: List[_]): Boolean = + @tailrec def listEq(a: List[?], b: List[?]): Boolean = (a eq b) || { val aEmpty = a.isEmpty val bEmpty = b.isEmpty @@ -667,7 +667,7 @@ case object Nil extends List[Nothing] { override def unzip[A1, A2](implicit asPair: Nothing -> (A1, A2)): (List[A1], List[A2]) = EmptyUnzip @transient - private[this] val EmptyUnzip = (Nil, Nil) + private val EmptyUnzip = (Nil, Nil) } /** diff --git a/library/src/scala/collection/immutable/ListMap.scala b/library/src/scala/collection/immutable/ListMap.scala index b6599369a1bd..2b77b779dffe 100644 --- a/library/src/scala/collection/immutable/ListMap.scala +++ b/library/src/scala/collection/immutable/ListMap.scala @@ -112,7 +112,7 @@ sealed class ListMap[K, +V] private[immutable] def next: ListMap[K, V] = throw new NoSuchElementException("next of empty map") override def foldRight[Z](z: Z)(op: ((K, V), Z) => Z): Z = ListMap.foldRightInternal(this, z, op) - override protected[this] def className = "ListMap" + override protected def className = "ListMap" } @@ -144,7 +144,7 @@ object ListMap extends MapFactory[ListMap] { override def size: Int = sizeInternal(this, 0) - @tailrec private[this] def sizeInternal(cur: ListMap[K, V], acc: Int): Int = + @tailrec private def sizeInternal(cur: ListMap[K, V], acc: Int): Int = if (cur.isEmpty) acc else sizeInternal(cur.next, acc + 1) @@ -155,21 +155,21 @@ object ListMap extends MapFactory[ListMap] { @throws[NoSuchElementException] override def apply(k: K): V = applyInternal(this, k) - @tailrec private[this] def applyInternal(cur: ListMap[K, V], k: K): V = + @tailrec private def applyInternal(cur: ListMap[K, V], k: K): V = if (cur.isEmpty) throw new NoSuchElementException("key not found: " + k) else if (k == cur.key) cur.value else applyInternal(cur.next, k) override def get(k: K): Option[V] = getInternal(this, k) - @tailrec private[this] def getInternal(cur: ListMap[K, V], k: K): Option[V] = + @tailrec private def getInternal(cur: ListMap[K, V], k: K): Option[V] = if (cur.isEmpty) None else if (k == cur.key) Some(cur.value) else getInternal(cur.next, k) override def contains(k: K): Boolean = containsInternal(this, k) - @tailrec private[this] def containsInternal(cur: ListMap[K, V], k: K): Boolean = + @tailrec private def containsInternal(cur: ListMap[K, V], k: K): Boolean = if (cur.isEmpty) false else if (k == cur.key) true else containsInternal(cur.next, k) @@ -225,7 +225,7 @@ object ListMap extends MapFactory[ListMap] { } } - @tailrec private[this] def removeInternal(k: K, cur: ListMap[K, V], acc: List[ListMap[K, V]]): ListMap[K, V] = + @tailrec private def removeInternal(k: K, cur: ListMap[K, V], acc: List[ListMap[K, V]]): ListMap[K, V] = if (cur.isEmpty) acc.last else if (k == cur.key) acc.foldLeft(cur.next) { (t, h) => new Node(h.key, h.value, t) } else removeInternal(k, cur.next, cur :: acc) @@ -288,8 +288,8 @@ object ListMap extends MapFactory[ListMap] { * $multipleResults */ private[immutable] final class ListMapBuilder[K, V] extends mutable.ReusableBuilder[(K, V), ListMap[K, V]] { - private[this] var isAliased: Boolean = false - private[this] var underlying: ListMap[K, V] = ListMap.empty + private var isAliased: Boolean = false + private var underlying: ListMap[K, V] = ListMap.empty override def clear(): Unit = { underlying = ListMap.empty @@ -305,7 +305,7 @@ private[immutable] final class ListMapBuilder[K, V] extends mutable.ReusableBuil override def addOne(elem: (K, V)): this.type = addOne(elem._1, elem._2) @tailrec - private[this] def insertValueAtKeyReturnFound(m: ListMap[K, V], key: K, value: V): Boolean = m match { + private def insertValueAtKeyReturnFound(m: ListMap[K, V], key: K, value: V): Boolean = m match { case n: ListMap.Node[K, V] => if (n.key == key) { n._value = value diff --git a/library/src/scala/collection/immutable/ListSet.scala b/library/src/scala/collection/immutable/ListSet.scala index ed08c69d1b37..8306aa4a4f5a 100644 --- a/library/src/scala/collection/immutable/ListSet.scala +++ b/library/src/scala/collection/immutable/ListSet.scala @@ -46,7 +46,7 @@ sealed class ListSet[A] with IterableFactoryDefaults[A, ListSet] with DefaultSerializable { - override protected[this] def className: String = "ListSet" + override protected def className: String = "ListSet" override def size: Int = 0 override def knownSize: Int = 0 @@ -79,7 +79,7 @@ sealed class ListSet[A] override def size = sizeInternal(this, 0) override def knownSize: Int = -1 - @tailrec private[this] def sizeInternal(n: ListSet[A], acc: Int): Int = + @tailrec private def sizeInternal(n: ListSet[A], acc: Int): Int = if (n.isEmpty) acc else sizeInternal(n.next, acc + 1) @@ -87,14 +87,14 @@ sealed class ListSet[A] override def contains(e: A): Boolean = containsInternal(this, e) - @tailrec private[this] def containsInternal(n: ListSet[A], e: A): Boolean = + @tailrec private def containsInternal(n: ListSet[A], e: A): Boolean = !n.isEmpty && (n.elem == e || containsInternal(n.next, e)) override def incl(e: A): ListSet[A] = if (contains(e)) this else new Node(e) override def excl(e: A): ListSet[A] = removeInternal(e, this, Nil) - @tailrec private[this] def removeInternal(k: A, cur: ListSet[A], acc: List[ListSet[A]]): ListSet[A] = + @tailrec private def removeInternal(k: A, cur: ListSet[A], acc: List[ListSet[A]]): ListSet[A] = if (cur.isEmpty) acc.last else if (k == cur.elem) acc.foldLeft(cur.next)((t, h) => new t.Node(h.elem)) else removeInternal(k, cur.next, cur :: acc) diff --git a/library/src/scala/collection/immutable/LongMap.scala b/library/src/scala/collection/immutable/LongMap.scala index fab52e1d1db2..a8634f4100b0 100644 --- a/library/src/scala/collection/immutable/LongMap.scala +++ b/library/src/scala/collection/immutable/LongMap.scala @@ -88,19 +88,19 @@ object LongMap { implicit def toFactory[V](dummy: LongMap.type): Factory[(Long, V), LongMap[V]] = ToFactory.asInstanceOf[Factory[(Long, V), LongMap[V]]] @SerialVersionUID(3L) - private[this] object ToFactory extends Factory[(Long, AnyRef), LongMap[AnyRef]] with Serializable { + private object ToFactory extends Factory[(Long, AnyRef), LongMap[AnyRef]] with Serializable { def fromSpecific(it: IterableOnce[(Long, AnyRef)]^): LongMap[AnyRef] = LongMap.from[AnyRef](it) def newBuilder: Builder[(Long, AnyRef), LongMap[AnyRef]] = LongMap.newBuilder[AnyRef] } implicit def toBuildFrom[V](factory: LongMap.type): BuildFrom[Any, (Long, V), LongMap[V]] = ToBuildFrom.asInstanceOf[BuildFrom[Any, (Long, V), LongMap[V]]] - private[this] object ToBuildFrom extends BuildFrom[Any, (Long, AnyRef), LongMap[AnyRef]] { + private object ToBuildFrom extends BuildFrom[Any, (Long, AnyRef), LongMap[AnyRef]] { def fromSpecific(from: Any)(it: IterableOnce[(Long, AnyRef)]^) = LongMap.from(it) def newBuilder(from: Any) = LongMap.newBuilder[AnyRef] } implicit def iterableFactory[V]: Factory[(Long, V), LongMap[V]] = toFactory(this) - implicit def buildFromLongMap[V]: BuildFrom[LongMap[_], (Long, V), LongMap[V]] = toBuildFrom(this) + implicit def buildFromLongMap[V]: BuildFrom[LongMap[?], (Long, V), LongMap[V]] = toBuildFrom(this) } // Iterator over a non-empty LongMap. @@ -258,7 +258,7 @@ sealed abstract class LongMap[+T] extends AbstractMap[Long, T] case LongMap.Nil => } - override protected[this] def className = "LongMap" + override protected def className = "LongMap" override def isEmpty = this eq LongMap.Nil override def knownSize: Int = if (isEmpty) 0 else super.knownSize @@ -489,5 +489,5 @@ sealed abstract class LongMap[+T] extends AbstractMap[Long, T] def collect[V2](pf: PartialFunction[(Long, T), (Long, V2)]): LongMap[V2] = strictOptimizedCollect(LongMap.newBuilder[V2], pf) - protected[this] def writeReplace(): AnyRef = new DefaultSerializationProxy(LongMap.toFactory[T](LongMap), this) + protected def writeReplace(): AnyRef = new DefaultSerializationProxy(LongMap.toFactory[T](LongMap), this) } diff --git a/library/src/scala/collection/immutable/Map.scala b/library/src/scala/collection/immutable/Map.scala index fc1f720c4865..b1276b7898b1 100644 --- a/library/src/scala/collection/immutable/Map.scala +++ b/library/src/scala/collection/immutable/Map.scala @@ -62,12 +62,12 @@ trait Map[K, +V] * @define coll immutable map * @define Coll `immutable.Map` */ -transparent trait MapOps[K, +V, +CC[X, +Y] <: MapOps[X, Y, CC, _], +C <: MapOps[K, V, CC, C]] +transparent trait MapOps[K, +V, +CC[X, +Y] <: MapOps[X, Y, CC, ?], +C <: MapOps[K, V, CC, C]] extends IterableOps[(K, V), Iterable, C] with collection.MapOps[K, V, CC, C] with caps.Pure { - protected def coll: C with CC[K, V] + protected def coll: C & CC[K, V] /** Removes a key from this map, returning a new map. * @@ -153,7 +153,7 @@ transparent trait MapOps[K, +V, +CC[X, +Y] <: MapOps[X, Y, CC, _], +C <: MapOps[ } -transparent trait StrictOptimizedMapOps[K, +V, +CC[X, +Y] <: MapOps[X, Y, CC, _], +C <: MapOps[K, V, CC, C]] +transparent trait StrictOptimizedMapOps[K, +V, +CC[X, +Y] <: MapOps[X, Y, CC, ?], +C <: MapOps[K, V, CC, C]] extends MapOps[K, V, CC, C] with collection.StrictOptimizedMapOps[K, V, CC, C] with StrictOptimizedIterableOps[(K, V), Iterable, C] { @@ -338,7 +338,7 @@ object Map extends MapFactory[Map] { } private abstract class Map2Iterator[A] extends AbstractIterator[A] { - private[this] var i = 0 + private var i = 0 override def hasNext: Boolean = i < 2 override def next(): A = { val result = i match { @@ -441,7 +441,7 @@ object Map extends MapFactory[Map] { } private abstract class Map3Iterator[A] extends AbstractIterator[A] { - private[this] var i = 0 + private var i = 0 override def hasNext: Boolean = i < 3 override def next(): A = { val result = i match { @@ -561,7 +561,7 @@ object Map extends MapFactory[Map] { } private abstract class Map4Iterator[A] extends AbstractIterator[A] { - private[this] var i = 0 + private var i = 0 override def hasNext: Boolean = i < 4 override def next(): A = { val result = i match { @@ -663,9 +663,9 @@ object Map extends MapFactory[Map] { abstract class AbstractMap[K, +V] extends scala.collection.AbstractMap[K, V] with Map[K, V] private[immutable] final class MapBuilderImpl[K, V] extends ReusableBuilder[(K, V), Map[K, V]] { - private[this] var elems: Map[K, V] = Map.empty - private[this] var switchedToHashMapBuilder: Boolean = false - private[this] var hashMapBuilder: HashMapBuilder[K, V] = _ + private var elems: Map[K, V] = Map.empty + private var switchedToHashMapBuilder: Boolean = false + private var hashMapBuilder: HashMapBuilder[K, V] = compiletime.uninitialized private[immutable] def getOrElse[V0 >: V](key: K, value: V0): V0 = if (hashMapBuilder ne null) hashMapBuilder.getOrElse(key, value) diff --git a/library/src/scala/collection/immutable/NumericRange.scala b/library/src/scala/collection/immutable/NumericRange.scala index c09b49810b24..f5c29028b820 100644 --- a/library/src/scala/collection/immutable/NumericRange.scala +++ b/library/src/scala/collection/immutable/NumericRange.scala @@ -58,15 +58,15 @@ sealed class NumericRange[T]( override def iterator: Iterator[T] = new NumericRange.NumericRangeIterator(this, num) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[T, S]): S with EfficientSplit = { + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[T, S]): S & EfficientSplit = { import scala.collection.convert._ import impl._ val s = shape.shape match { case StepperShape.IntShape => new IntNumericRangeStepper (this.asInstanceOf[NumericRange[Int]], 0, length) case StepperShape.LongShape => new LongNumericRangeStepper (this.asInstanceOf[NumericRange[Long]], 0, length) - case _ => shape.parUnbox(new AnyNumericRangeStepper[T](this, 0, length).asInstanceOf[AnyStepper[T] with EfficientSplit]) + case _ => shape.parUnbox(new AnyNumericRangeStepper[T](this, 0, length).asInstanceOf[AnyStepper[T] & EfficientSplit]) } - s.asInstanceOf[S with EfficientSplit] + s.asInstanceOf[S & EfficientSplit] } @@ -123,7 +123,7 @@ sealed class NumericRange[T]( } } - private[this] def indexOfTyped(elem: T, from: Int): Int = + private def indexOfTyped(elem: T, from: Int): Int = posOf(elem) match { case pos if pos >= from => pos case _ => -1 @@ -133,7 +133,7 @@ sealed class NumericRange[T]( try indexOfTyped(elem.asInstanceOf[T], from) catch { case _: ClassCastException => super.indexOf(elem, from) } - private[this] def lastIndexOfTyped(elem: T, end: Int): Int = + private def lastIndexOfTyped(elem: T, end: Int): Int = posOf(elem) match { case pos if pos <= end => pos case _ => -1 @@ -143,7 +143,7 @@ sealed class NumericRange[T]( try lastIndexOfTyped(elem.asInstanceOf[T], end) catch { case _: ClassCastException => super.lastIndexOf(elem, end) } - private[this] def posOf(i: T): Int = + private def posOf(i: T): Int = /* If i is in this NumericRange, its position can simply be calculated by taking the amount of values up till i. NumericRange.count does this in an most efficient manner. @@ -277,14 +277,14 @@ sealed class NumericRange[T]( if ((ord eq num) || defaultOrdering.get(num).exists(ord eq _)) { if (num.sign(step) > zero) head else last - } else super.min(ord) + } else super.min(using ord) override def max[T1 >: T](implicit ord: Ordering[T1]): T = // See comment for fast path in min(). if ((ord eq num) || defaultOrdering.get(num).exists(ord eq _)) { if (num.sign(step) > zero) last else head - } else super.max(ord) + } else super.max(using ord) // a well-typed contains method. def containsTyped(x: T): Boolean = @@ -369,7 +369,7 @@ sealed class NumericRange[T]( s"${empty}NumericRange $start $preposition $end$stepped" } - override protected[this] def className = "NumericRange" + override protected def className = "NumericRange" } /** A companion object for numeric ranges. @@ -514,7 +514,7 @@ object NumericRange { def inclusive[T](start: T, end: T, step: T)(implicit num: Integral[T]): Inclusive[T] = new Inclusive(start, end, step) - private[collection] val defaultOrdering = Map[Numeric[_], Ordering[_]]( + private[collection] val defaultOrdering = Map[Numeric[?], Ordering[?]]( Numeric.BigIntIsIntegral -> Ordering.BigInt, Numeric.IntIsIntegral -> Ordering.Int, Numeric.ShortIsIntegral -> Ordering.Short, @@ -528,9 +528,9 @@ object NumericRange { private final class NumericRangeIterator[T](self: NumericRange[T], num: Integral[T]) extends AbstractIterator[T] with Serializable { import num.mkNumericOps - private[this] var _hasNext = !self.isEmpty - private[this] var _next: T = self.start - private[this] val lastElement: T = if (_hasNext) self.last else self.start + private var _hasNext = !self.isEmpty + private var _next: T = self.start + private val lastElement: T = if (_hasNext) self.last else self.start override def knownSize: Int = if (_hasNext) num.toInt((lastElement - _next) / self.step) + 1 else 0 def hasNext: Boolean = _hasNext def next(): T = { diff --git a/library/src/scala/collection/immutable/Queue.scala b/library/src/scala/collection/immutable/Queue.scala index 326d3c7c56a6..0ddfe40c77f6 100644 --- a/library/src/scala/collection/immutable/Queue.scala +++ b/library/src/scala/collection/immutable/Queue.scala @@ -113,7 +113,7 @@ sealed class Queue[+A] protected(protected val in: List[A], protected val out: L override def exists(p: A => Boolean): Boolean = in.exists(p) || out.exists(p) - override protected[this] def className = "Queue" + override protected def className = "Queue" /** Returns the length of the queue. */ override def length: Int = in.length + out.length diff --git a/library/src/scala/collection/immutable/Range.scala b/library/src/scala/collection/immutable/Range.scala index 45e99ff3badc..612b551a5fd5 100644 --- a/library/src/scala/collection/immutable/Range.scala +++ b/library/src/scala/collection/immutable/Range.scala @@ -75,7 +75,7 @@ sealed abstract class Range( final override def iterator: Iterator[Int] = new RangeIterator(start, step, lastElement, isEmpty) - override final def stepper[S <: Stepper[_]](implicit shape: StepperShape[Int, S]): S with EfficientSplit = { + override final def stepper[S <: Stepper[?]](implicit shape: StepperShape[Int, S]): S & EfficientSplit = { val st = new RangeStepper(start, step, 0, length) val r = if (shape.shape == StepperShape.IntShape) st @@ -83,7 +83,7 @@ sealed abstract class Range( assert(shape.shape == StepperShape.ReferenceShape, s"unexpected StepperShape: $shape") AnyStepper.ofParIntStepper(st) } - r.asInstanceOf[S with EfficientSplit] + r.asInstanceOf[S & EfficientSplit] } def isInclusive: Boolean @@ -109,7 +109,7 @@ sealed abstract class Range( * This interpretation allows to represent all values with the correct * modular arithmetics, which streamlines the usage sites. */ - private[this] val numRangeElements: Int = { + private val numRangeElements: Int = { val stepSign = step >> 31 // if (step >= 0) 0 else -1 val gap = ((end - start) ^ stepSign) - stepSign // if (step >= 0) (end - start) else -(end - start) val absStep = (step ^ stepSign) - stepSign // if (step >= 0) step else -step @@ -140,7 +140,7 @@ sealed abstract class Range( * make sense, but won't error out. */ @inline - private[this] def locationAfterN(n: Int): Int = { + private def locationAfterN(n: Int): Int = { /* If `step >= 0`, we interpret `step * n` as an unsigned multiplication, * and the addition as a mixed `(signed, unsigned) -> signed` operation. * With those interpretation, they do not overflow, assuming the @@ -159,7 +159,7 @@ sealed abstract class Range( * * For empty ranges, this value is nonsensical. */ - private[this] val lastElement: Int = { + private val lastElement: Int = { /* Since we can assume the range is non-empty, `(numRangeElements - 1)` * is a valid unsigned value in the full int range. The general formula is * therefore `locationAfterN(numRangeElements - 1)`. @@ -231,12 +231,12 @@ sealed abstract class Range( // should not trigger an exception. So the calculation is delayed, // which means it will not fail fast for those cases where failing was // correct. - private[this] def validateMaxLength(): Unit = { + private def validateMaxLength(): Unit = { if (numRangeElements <= 0 && !isEmpty) fail() } - private[this] def description = "%d %s %d by %s".format(start, if (isInclusive) "to" else "until", end, step) - private[this] def fail() = throw new IllegalArgumentException(description + ": seqs cannot contain more than Int.MaxValue elements.") + private def description = "%d %s %d by %s".format(start, if (isInclusive) "to" else "until", end, step) + private def fail() = throw new IllegalArgumentException(description + ": seqs cannot contain more than Int.MaxValue elements.") @throws[IndexOutOfBoundsException] final def apply(idx: Int): Int = { @@ -279,7 +279,7 @@ sealed abstract class Range( case _ => super.lastIndexOf(elem, end) } - private[this] def posOf(i: Int): Int = + private def posOf(i: Int): Int = if (contains(i)) (i - start) / step else -1 override def sameElements[B >: Int](that: IterableOnce[B]^): Boolean = that match { @@ -300,7 +300,7 @@ sealed abstract class Range( * * This method returns nonsensical results if `n < 0` or if `this.isEmpty`. */ - @inline private[this] def greaterEqualNumRangeElements(n: Int): Boolean = + @inline private def greaterEqualNumRangeElements(n: Int): Boolean = (n ^ Int.MinValue) > ((numRangeElements - 1) ^ Int.MinValue) // unsigned comparison /** Creates a new range containing the first `n` elements of this range. @@ -344,7 +344,7 @@ sealed abstract class Range( } // Advance from the start while we meet the given test - private[this] def argTakeWhile(p: Int => Boolean): Long = { + private def argTakeWhile(p: Int => Boolean): Long = { if (isEmpty) start else { var current = start @@ -410,7 +410,7 @@ sealed abstract class Range( // like "end + 1" or "end - 1" because ranges involving Int.{ MinValue, MaxValue } // will overflow. This creates an exclusive range where start == end // based on the given value. - private[this] def newEmptyRange(value: Int) = new Range.Exclusive(value, value, step) + private def newEmptyRange(value: Int) = new Range.Exclusive(value, value, step) /** Returns the reverse of this range. */ @@ -470,7 +470,7 @@ sealed abstract class Range( } else if (Ordering.Int isReverseOf ord) { if (step > 0) last else head - } else super.min(ord) + } else super.min(using ord) final override def max[A1 >: Int](implicit ord: Ordering[A1]): Int = if (ord eq Ordering.Int) { @@ -479,11 +479,11 @@ sealed abstract class Range( } else if (Ordering.Int isReverseOf ord) { if (step > 0) head else last - } else super.max(ord) + } else super.max(using ord) override def tails: Iterator[Range] = new AbstractIterator[Range] { - private[this] var i = 0 + private var i = 0 override def hasNext = i <= Range.this.length override def next() = { if (hasNext) { @@ -498,7 +498,7 @@ sealed abstract class Range( override def inits: Iterator[Range] = new AbstractIterator[Range] { - private[this] var i = 0 + private var i = 0 override def hasNext = i <= Range.this.length override def next() = { if (hasNext) { @@ -543,7 +543,7 @@ sealed abstract class Range( s"${prefix}Range $start $preposition $end$stepped" } - override protected[this] def className = "Range" + override protected def className = "Range" override def distinct: Range = this @@ -554,7 +554,7 @@ sealed abstract class Range( } else { val s = size new AbstractIterator[Range] { - private[this] var i = 0 + private var i = 0 override def hasNext = Range.this.length > i override def next() = if (hasNext) { @@ -576,7 +576,7 @@ sealed abstract class Range( reverse } } else { - super.sorted(ord) + super.sorted(using ord) } } @@ -701,8 +701,8 @@ private class RangeIterator( lastElement: Int, initiallyEmpty: Boolean ) extends AbstractIterator[Int] with Serializable { self => - private[this] var _hasNext: Boolean = !initiallyEmpty - private[this] var _next: Int = start + private var _hasNext: Boolean = !initiallyEmpty + private var _next: Int = start override def knownSize: Int = if (_hasNext) (lastElement - _next) / step + 1 else 0 def hasNext: Boolean = _hasNext @throws[NoSuchElementException] diff --git a/library/src/scala/collection/immutable/RedBlackTree.scala b/library/src/scala/collection/immutable/RedBlackTree.scala index eb55757accb2..b343d521a83c 100644 --- a/library/src/scala/collection/immutable/RedBlackTree.scala +++ b/library/src/scala/collection/immutable/RedBlackTree.scala @@ -29,8 +29,8 @@ import scala.runtime.Statics.releaseFence * optimizations behind a reasonably clean API. */ private[collection] object RedBlackTree { - def validate[A](tree: Tree[A, _] | Null)(implicit ordering: Ordering[A]): tree.type = { - def impl(tree: Tree[A, _], keyProp: A => Boolean): Int = { + def validate[A](tree: Tree[A, ?] | Null)(implicit ordering: Ordering[A]): tree.type = { + def impl(tree: Tree[A, ?], keyProp: A => Boolean): Int = { assert(keyProp(tree.key), s"key check failed: $tree") if (tree.isRed) { assert(tree.left == null || tree.left.nn.isBlack, s"red-red left $tree") @@ -45,9 +45,9 @@ private[collection] object RedBlackTree { tree } - def isEmpty(tree: Tree[_, _] | Null): Boolean = tree eq null + def isEmpty(tree: Tree[?, ?] | Null): Boolean = tree eq null - def contains[A: Ordering](tree: Tree[A, _] | Null, x: A): Boolean = lookup(tree, x) ne null + def contains[A: Ordering](tree: Tree[A, ?] | Null, x: A): Boolean = lookup(tree, x) ne null def get[A: Ordering, B](tree: Tree[A, B] | Null, x: A): Option[B] = lookup(tree, x) match { case null => None case found => Some(found.value) @@ -71,7 +71,7 @@ private[collection] object RedBlackTree { } /** Create a new balanced tree where `newLeft` replaces `tree.left`. * tree and newLeft are never null */ - protected[this] final def mutableBalanceLeft[A1, B, B1 >: B](tree: Tree[A1, B], newLeft: Tree[A1, B1]): Tree[A1, B1] = { + protected final def mutableBalanceLeft[A1, B, B1 >: B](tree: Tree[A1, B], newLeft: Tree[A1, B1]): Tree[A1, B1] = { // Parameter trees // tree | newLeft // -- KV R | nl.L nl.KV nl.R @@ -114,7 +114,7 @@ private[collection] object RedBlackTree { } /** Create a new balanced tree where `newRight` replaces `tree.right`. * tree and newRight are never null */ - protected[this] final def mutableBalanceRight[A1, B, B1 >: B](tree: Tree[A1, B], newRight: Tree[A1, B1]): Tree[A1, B1] = { + protected final def mutableBalanceRight[A1, B, B1 >: B](tree: Tree[A1, B], newRight: Tree[A1, B1]): Tree[A1, B1] = { // Parameter trees // tree | newRight // L KV -- | nr.L nr.KV nr.R @@ -159,7 +159,7 @@ private[collection] object RedBlackTree { } } private[immutable] class SetHelper[A](implicit ordering: Ordering[A]) extends Helper[A] { - protected[this] final def mutableUpd(tree: Tree[A, Any] | Null, k: A): Tree[A, Any] = + protected final def mutableUpd(tree: Tree[A, Any] | Null, k: A): Tree[A, Any] = if (tree eq null) { mutableRedTree(k, (), null, null) } else if (k.asInstanceOf[AnyRef] eq tree.key.asInstanceOf[AnyRef]) { @@ -174,7 +174,7 @@ private[collection] object RedBlackTree { } } private[immutable] class MapHelper[A, B](implicit ordering: Ordering[A]) extends Helper[A] { - protected[this] final def mutableUpd[B1 >: B](tree: Tree[A, B] | Null, k: A, v: B1): Tree[A, B1] = + protected final def mutableUpd[B1 >: B](tree: Tree[A, B] | Null, k: A, v: B1): Tree[A, B1] = if (tree eq null) { mutableRedTree(k, v, null, null) } else if (k.asInstanceOf[AnyRef] eq tree.key.asInstanceOf[AnyRef]) { @@ -189,7 +189,7 @@ private[collection] object RedBlackTree { } } - def count(tree: Tree[_, _] | Null) = if (tree eq null) 0 else tree.count + def count(tree: Tree[?, ?] | Null) = if (tree eq null) 0 else tree.count def update[A: Ordering, B, B1 >: B](tree: Tree[A, B] | Null, k: A, v: B1, overwrite: Boolean): Tree[A, B1] | Null = blacken(upd(tree, k, v, overwrite)) def delete[A: Ordering, B](tree: Tree[A, B] | Null, k: A): Tree[A, B] | Null = blacken(del(tree, k)) def rangeImpl[A: Ordering, B](tree: Tree[A, B] | Null, from: Option[A], until: Option[A]): Tree[A, B] | Null = (from, until) match { @@ -289,15 +289,15 @@ private[collection] object RedBlackTree { else a.count == b.count && (new EqualsIterator(a)).sameEntries(new EqualsIterator(b)) } - private[this] def _foreach[A, B, U](tree: Tree[A, B], f: ((A, B)) => U): Unit = { + private def _foreach[A, B, U](tree: Tree[A, B], f: ((A, B)) => U): Unit = { if (tree.left ne null) _foreach(tree.left.nn, f) f((tree.key, tree.value)) if (tree.right ne null) _foreach(tree.right.nn, f) } - def foreachKey[A, U](tree: Tree[A,_] | Null, f: A => U):Unit = if (tree ne null) _foreachKey(tree,f) + def foreachKey[A, U](tree: Tree[A, ?] | Null, f: A => U):Unit = if (tree ne null) _foreachKey(tree,f) - private[this] def _foreachKey[A, U](tree: Tree[A, _], f: A => U): Unit = { + private def _foreachKey[A, U](tree: Tree[A, ?], f: A => U): Unit = { if (tree.left ne null) _foreachKey(tree.left.nn, f) f((tree.key)) if (tree.right ne null) _foreachKey(tree.right.nn, f) @@ -305,14 +305,14 @@ private[collection] object RedBlackTree { def foreachEntry[A, B, U](tree: Tree[A,B] | Null, f: (A, B) => U):Unit = if (tree ne null) _foreachEntry(tree,f) - private[this] def _foreachEntry[A, B, U](tree: Tree[A, B], f: (A, B) => U): Unit = { + private def _foreachEntry[A, B, U](tree: Tree[A, B], f: (A, B) => U): Unit = { if (tree.left ne null) _foreachEntry(tree.left.nn, f) f(tree.key, tree.value) if (tree.right ne null) _foreachEntry(tree.right.nn, f) } def iterator[A: Ordering, B](tree: Tree[A, B] | Null, start: Option[A] = None): Iterator[(A, B)] = new EntriesIterator(tree, start) - def keysIterator[A: Ordering](tree: Tree[A, _] | Null, start: Option[A] = None): Iterator[A] = new KeysIterator(tree, start) + def keysIterator[A: Ordering](tree: Tree[A, ?] | Null, start: Option[A] = None): Iterator[A] = new KeysIterator(tree, start) def valuesIterator[A: Ordering, B](tree: Tree[A, B] | Null, start: Option[A] = None): Iterator[B] = new ValuesIterator(tree, start) @tailrec @@ -323,25 +323,25 @@ private[collection] object RedBlackTree { else tree } - def isBlack(tree: Tree[_, _] | Null) = (tree eq null) || tree.isBlack + def isBlack(tree: Tree[?, ?] | Null) = (tree eq null) || tree.isBlack - @`inline` private[this] def isRedTree(tree: Tree[_, _] | Null) = (tree ne null) && tree.isRed - @`inline` private[this] def isBlackTree(tree: Tree[_, _] | Null) = (tree ne null) && tree.isBlack + @`inline` private def isRedTree(tree: Tree[?, ?] | Null) = (tree ne null) && tree.isRed + @`inline` private def isBlackTree(tree: Tree[?, ?] | Null) = (tree ne null) && tree.isBlack - private[this] def blacken[A, B](t: Tree[A, B] | Null): Tree[A, B] | Null = if (t eq null) null else t.black + private def blacken[A, B](t: Tree[A, B] | Null): Tree[A, B] | Null = if (t eq null) null else t.black // Blacken if the tree is red and has a red child. This is necessary when using methods such as `upd` or `updNth` // for building subtrees. Use `blacken` instead when building top-level trees. - private[this] def maybeBlacken[A, B](t: Tree[A, B]): Tree[A, B] = + private def maybeBlacken[A, B](t: Tree[A, B]): Tree[A, B] = if(isBlack(t)) t else if(isRedTree(t.left) || isRedTree(t.right)) t.black else t - private[this] def mkTree[A, B](isBlack: Boolean, key: A, value: B, left: Tree[A, B] | Null, right: Tree[A, B] | Null) = { + private def mkTree[A, B](isBlack: Boolean, key: A, value: B, left: Tree[A, B] | Null, right: Tree[A, B] | Null) = { val sizeAndColour = sizeOf(left) + sizeOf(right) + 1 | (if(isBlack) initialBlackCount else initialRedCount) new Tree(key, value.asInstanceOf[AnyRef], left, right, sizeAndColour) } /** Create a new balanced tree where `newLeft` replaces `tree.left`. */ - private[this] def balanceLeft[A, B1](tree: Tree[A, B1], newLeft: Tree[A, B1]): Tree[A, B1] = { + private def balanceLeft[A, B1](tree: Tree[A, B1], newLeft: Tree[A, B1]): Tree[A, B1] = { // Parameter trees // tree | newLeft // -- KV R | nl.L nl.KV nl.R @@ -382,7 +382,7 @@ private[collection] object RedBlackTree { } } /** Create a new balanced tree where `newRight` replaces `tree.right`. */ - private[this] def balanceRight[A, B1](tree: Tree[A, B1], newRight: Tree[A, B1]): Tree[A, B1] = { + private def balanceRight[A, B1](tree: Tree[A, B1], newRight: Tree[A, B1]): Tree[A, B1] = { // Parameter trees // tree | newRight // L KV -- | nr.L nr.KV nr.R @@ -423,7 +423,7 @@ private[collection] object RedBlackTree { } } - private[this] def upd[A, B, B1 >: B](tree: Tree[A, B] | Null, k: A, v: B1, overwrite: Boolean)(implicit ordering: Ordering[A]): Tree[A, B1] = if (tree eq null) { + private def upd[A, B, B1 >: B](tree: Tree[A, B] | Null, k: A, v: B1, overwrite: Boolean)(implicit ordering: Ordering[A]): Tree[A, B1] = if (tree eq null) { RedTree[A, B1](k, v, null, null) } else if (k.asInstanceOf[AnyRef] eq tree.key.asInstanceOf[AnyRef]) { if (overwrite) @@ -439,7 +439,7 @@ private[collection] object RedBlackTree { tree.withV(v) else tree } - private[this] def updNth[A, B, B1 >: B](tree: Tree[A, B] | Null, idx: Int, k: A, v: B1): Tree[A, B1] = if (tree eq null) { + private def updNth[A, B, B1 >: B](tree: Tree[A, B] | Null, idx: Int, k: A, v: B1): Tree[A, B1] = if (tree eq null) { RedTree(k, v, null: Tree[A, B1] | Null, null: Tree[A, B1] | Null) } else { val rank = count(tree.left) + 1 @@ -450,7 +450,7 @@ private[collection] object RedBlackTree { else tree } - private[this] def doFrom[A, B](tree: Tree[A, B] | Null, from: A)(implicit ordering: Ordering[A]): Tree[A, B] | Null = { + private def doFrom[A, B](tree: Tree[A, B] | Null, from: A)(implicit ordering: Ordering[A]): Tree[A, B] | Null = { if (tree eq null) return null if (ordering.lt(tree.key, from)) return doFrom(tree.right, from) val newLeft = doFrom(tree.left, from) @@ -458,7 +458,7 @@ private[collection] object RedBlackTree { else if (newLeft eq null) maybeBlacken(upd(tree.right, tree.key, tree.value, overwrite = false)) else join(newLeft, tree.key, tree.value, tree.right) } - private[this] def doTo[A, B](tree: Tree[A, B] | Null, to: A)(implicit ordering: Ordering[A]): Tree[A, B] | Null = { + private def doTo[A, B](tree: Tree[A, B] | Null, to: A)(implicit ordering: Ordering[A]): Tree[A, B] | Null = { if (tree eq null) return null if (ordering.lt(to, tree.key)) return doTo(tree.left, to) val newRight = doTo(tree.right, to) @@ -466,7 +466,7 @@ private[collection] object RedBlackTree { else if (newRight eq null) maybeBlacken(upd(tree.left, tree.key, tree.value, overwrite = false)) else join(tree.left, tree.key, tree.value, newRight) } - private[this] def doUntil[A, B](tree: Tree[A, B] | Null, until: A)(implicit ordering: Ordering[A]): Tree[A, B] | Null = { + private def doUntil[A, B](tree: Tree[A, B] | Null, until: A)(implicit ordering: Ordering[A]): Tree[A, B] | Null = { if (tree eq null) return null if (ordering.lteq(until, tree.key)) return doUntil(tree.left, until) val newRight = doUntil(tree.right, until) @@ -475,7 +475,7 @@ private[collection] object RedBlackTree { else join(tree.left, tree.key, tree.value, newRight) } - private[this] def doRange[A, B](tree: Tree[A, B] | Null, from: A, until: A)(implicit ordering: Ordering[A]): Tree[A, B] | Null = { + private def doRange[A, B](tree: Tree[A, B] | Null, from: A, until: A)(implicit ordering: Ordering[A]): Tree[A, B] | Null = { if (tree eq null) return null if (ordering.lt(tree.key, from)) return doRange(tree.right, from, until) if (ordering.lteq(until, tree.key)) return doRange(tree.left, from, until) @@ -487,7 +487,7 @@ private[collection] object RedBlackTree { else join(newLeft, tree.key, tree.value, newRight) } - private[this] def doDrop[A, B](tree: Tree[A, B] | Null, n: Int): Tree[A, B] | Null = + private def doDrop[A, B](tree: Tree[A, B] | Null, n: Int): Tree[A, B] | Null = if((tree eq null) || (n <= 0)) tree else if(n >= tree.count) null else { @@ -497,7 +497,7 @@ private[collection] object RedBlackTree { else join(doDrop(tree.left, n), tree.key, tree.value, tree.right) } - private[this] def doTake[A, B](tree: Tree[A, B] | Null, n: Int): Tree[A, B] | Null = + private def doTake[A, B](tree: Tree[A, B] | Null, n: Int): Tree[A, B] | Null = if((tree eq null) || (n <= 0)) null else if(n >= tree.count) tree else { @@ -507,7 +507,7 @@ private[collection] object RedBlackTree { else join(tree.left, tree.key, tree.value, doTake(tree.right, n-l-1)) } - private[this] def doSlice[A, B](tree: Tree[A, B] | Null, from: Int, until: Int): Tree[A, B] | Null = + private def doSlice[A, B](tree: Tree[A, B] | Null, from: Int, until: Int): Tree[A, B] | Null = if((tree eq null) || (from >= until) || (from >= tree.count) || (until <= 0)) null else if((from <= 0) && (until >= tree.count)) tree else { @@ -558,8 +558,8 @@ private[collection] object RedBlackTree { private[immutable] final class Tree[A, +B]( @(`inline` @getter @setter) private var _key: A, @(`inline` @getter @setter) private var _value: AnyRef | Null, - @(`inline` @getter @setter) private var _left: Tree[A, _] | Null, - @(`inline` @getter @setter) private var _right: Tree[A, _] | Null, + @(`inline` @getter @setter) private var _left: Tree[A, ?] | Null, + @(`inline` @getter @setter) private var _right: Tree[A, ?] | Null, @(`inline` @getter @setter) private var _count: Int) { @`inline` private[RedBlackTree] def isMutable: Boolean = (_count & colourMask) == 0 @@ -572,7 +572,7 @@ private[collection] object RedBlackTree { @`inline` private def mutableRetainingColour = _count & colourBit //inlined here to avoid outer object null checks - @`inline` private[RedBlackTree] final def sizeOf(tree: Tree[_,_] | Null) = if (tree eq null) 0 else tree.count + @`inline` private[RedBlackTree] final def sizeOf(tree: Tree[?, ?] | Null) = if (tree eq null) 0 else tree.count @`inline` private[immutable] final def key = _key @`inline` private[immutable] final def value = _value.asInstanceOf[B] @`inline` private[immutable] final def left = _left.asInstanceOf[Tree[A, B] | Null] @@ -800,7 +800,7 @@ private[collection] object RedBlackTree { val size = sizeOf(left) + sizeOf(right) + 1 new Tree(key, value.asInstanceOf[AnyRef], left, right, initialBlackCount | size) } - @`inline` private def sizeOf(tree:Tree[_,_] | Null) = if (tree eq null) 0 else tree.count + @`inline` private def sizeOf(tree:Tree[?, ?] | Null) = if (tree eq null) 0 else tree.count //immutable APIs //assertions - uncomment decls and callers when changing functionality // private def devTimeAssert(assertion: Boolean) = { @@ -810,8 +810,8 @@ private[collection] object RedBlackTree { // private def assertNotMutable(t:Tree[_,_]) = { // devTimeAssert ((t eq null) || t.count > 0) // } - private[this] abstract class TreeIterator[A, B, R](root: Tree[A, B] | Null, start: Option[A])(protected implicit val ordering: Ordering[A]) extends AbstractIterator[R] { - protected[this] def nextResult(tree: Tree[A, B]): R + private abstract class TreeIterator[A, B, R](root: Tree[A, B] | Null, start: Option[A])(protected implicit val ordering: Ordering[A]) extends AbstractIterator[R] { + protected def nextResult(tree: Tree[A, B]): R override def hasNext: Boolean = lookahead ne null @@ -830,7 +830,7 @@ private[collection] object RedBlackTree { else if (tree.left eq null) tree else findLeftMostOrPopOnEmpty(goLeft(tree)) - @`inline` private[this] def pushNext(tree: Tree[A, B]): Unit = { + @`inline` private def pushNext(tree: Tree[A, B]): Unit = { stackOfNexts.nn(index) = tree index += 1 } @@ -839,7 +839,7 @@ private[collection] object RedBlackTree { stackOfNexts.nn(index) } - protected[this] val stackOfNexts: Array[Tree[A, B] | Null] | Null = if (root eq null) null else { + protected val stackOfNexts: Array[Tree[A, B] | Null] | Null = if (root eq null) null else { /* * According to "Ralf Hinze. Constructing red-black trees" [https://www.cs.ox.ac.uk/ralf.hinze/publications/#P5] * the maximum height of a red-black tree is 2*log_2(n + 2) - 2. @@ -852,7 +852,7 @@ private[collection] object RedBlackTree { val maximumHeight = 2 * (32 - Integer.numberOfLeadingZeros(root.count + 2 - 1)) - 2 new Array[Tree[A, B] | Null](maximumHeight) } - private[this] var index = 0 + private var index = 0 protected var lookahead: Tree[A, B] | Null = if (start.isDefined) startFrom(start.get) else findLeftMostOrPopOnEmpty(root) /** @@ -861,7 +861,7 @@ private[collection] object RedBlackTree { * to the ordering. Along the way build up the iterator's path stack so that "next" * functionality works. */ - private[this] def startFrom(key: A) : Tree[A,B] | Null = if (root eq null) null else { + private def startFrom(key: A) : Tree[A,B] | Null = if (root eq null) null else { @tailrec def find(tree: Tree[A, B] | Null): Tree[A, B] | Null = if (tree eq null) popNext() else find( @@ -871,7 +871,7 @@ private[collection] object RedBlackTree { find(root) } - @`inline` private[this] def goLeft(tree: Tree[A, B]) = { + @`inline` private def goLeft(tree: Tree[A, B]) = { pushNext(tree) tree.left } @@ -879,7 +879,7 @@ private[collection] object RedBlackTree { @`inline` protected final def goRight(tree: Tree[A, B]) = tree.right } - private[this] class EqualsIterator[A: Ordering, B](tree: Tree[A, B]) extends TreeIterator[A, B, Unit](tree, None) { + private class EqualsIterator[A: Ordering, B](tree: Tree[A, B]) extends TreeIterator[A, B, Unit](tree, None) { override def nextResult(tree: Tree[A, B]): Nothing = ??? def sameKeys[X](that:EqualsIterator[A,X]): Boolean = { @@ -927,15 +927,15 @@ private[collection] object RedBlackTree { equal && (this.lookahead eq null) && (that.lookahead eq null) } } - private[this] class EntriesIterator[A: Ordering, B](tree: Tree[A, B] | Null, focus: Option[A]) extends TreeIterator[A, B, (A, B)](tree, focus) { + private class EntriesIterator[A: Ordering, B](tree: Tree[A, B] | Null, focus: Option[A]) extends TreeIterator[A, B, (A, B)](tree, focus) { override def nextResult(tree: Tree[A, B]) = (tree.key, tree.value) } - private[this] class KeysIterator[A: Ordering, B](tree: Tree[A, B] | Null, focus: Option[A]) extends TreeIterator[A, B, A](tree, focus) { + private class KeysIterator[A: Ordering, B](tree: Tree[A, B] | Null, focus: Option[A]) extends TreeIterator[A, B, A](tree, focus) { override def nextResult(tree: Tree[A, B]) = tree.key } - private[this] class ValuesIterator[A: Ordering, B](tree: Tree[A, B] | Null, focus: Option[A]) extends TreeIterator[A, B, B](tree, focus) { + private class ValuesIterator[A: Ordering, B](tree: Tree[A, B] | Null, focus: Option[A]) extends TreeIterator[A, B, B](tree, focus) { override def nextResult(tree: Tree[A, B]) = tree.value } @@ -1005,7 +1005,7 @@ private[collection] object RedBlackTree { blacken(fk(t)) } - private[this] val null2 = (null, null) + private val null2 = (null, null) def partitionEntries[A, B](t: Tree[A, B] | Null, p: (A, B) => Boolean): (Tree[A, B] | Null, Tree[A, B] | Null) = if(t eq null) (null, null) else { if (t eq null) null2 @@ -1051,7 +1051,7 @@ private[collection] object RedBlackTree { // Constructing Red-Black Trees, Ralf Hinze: [[https://www.cs.ox.ac.uk/ralf.hinze/publications/WAAAPL99b.ps.gz]] // Red-Black Trees in a Functional Setting, Chris Okasaki: [[https://wiki.rice.edu/confluence/download/attachments/2761212/Okasaki-Red-Black.pdf]] */ - private[this] def del[A, B](tree: Tree[A, B] | Null, k: A)(implicit ordering: Ordering[A]): Tree[A, B] | Null = if (tree eq null) null else { + private def del[A, B](tree: Tree[A, B] | Null, k: A)(implicit ordering: Ordering[A]): Tree[A, B] | Null = if (tree eq null) null else { val cmp = ordering.compare(k, tree.key) if (cmp < 0) { val newLeft = del(tree.left, k) @@ -1066,7 +1066,7 @@ private[collection] object RedBlackTree { } else append(tree.left, tree.right) } - private[this] def balance[A, B](tree: Tree[A,B], tl: Tree[A, B] | Null, tr: Tree[A, B] | Null): Tree[A, B] = + private def balance[A, B](tree: Tree[A,B], tl: Tree[A, B] | Null, tr: Tree[A, B] | Null): Tree[A, B] = if (isRedTree(tl)) { if (isRedTree(tr)) tree.redWithLeftRight(tl.nn.black, tr.nn.black) else if (isRedTree(tl.nn.left)) tl.nn.withLeftRight(tl.nn.left.nn.black, tree.blackWithLeftRight(tl.nn.right, tr)) @@ -1078,14 +1078,14 @@ private[collection] object RedBlackTree { else tree.blackWithLeftRight(tl, tr) } else tree.blackWithLeftRight(tl, tr) - private[this] def balLeft[A, B](tree: Tree[A,B], tl: Tree[A, B] | Null, tr: Tree[A, B] | Null): Tree[A, B] = + private def balLeft[A, B](tree: Tree[A,B], tl: Tree[A, B] | Null, tr: Tree[A, B] | Null): Tree[A, B] = if (isRedTree(tl)) tree.redWithLeftRight(tl.nn.black, tr) else if (isBlackTree(tr)) balance(tree, tl, tr.nn.red) else if (isRedTree(tr) && isBlackTree(tr.nn.left)) tr.nn.left.nn.redWithLeftRight(tree.blackWithLeftRight(tl, tr.nn.left.nn.left), balance(tr.nn, tr.nn.left.nn.right, tr.nn.right.nn.red)) else sys.error("Defect: invariance violation") - private[this] def balRight[A, B](tree: Tree[A,B], tl: Tree[A, B] | Null, tr: Tree[A, B] | Null): Tree[A, B] = + private def balRight[A, B](tree: Tree[A,B], tl: Tree[A, B] | Null, tr: Tree[A, B] | Null): Tree[A, B] = if (isRedTree(tr)) tree.redWithLeftRight(tl, tr.nn.black) else if (isBlackTree(tl)) balance(tree, tl.nn.red, tr) else if (isRedTree(tl) && isBlackTree(tl.nn.right)) @@ -1093,7 +1093,7 @@ private[collection] object RedBlackTree { else sys.error("Defect: invariance violation") /** `append` is similar to `join2` but requires that both subtrees have the same black height */ - private[this] def append[A, B](tl: Tree[A, B] | Null, tr: Tree[A, B] | Null): Tree[A, B] | Null = { + private def append[A, B](tl: Tree[A, B] | Null, tr: Tree[A, B] | Null): Tree[A, B] | Null = { if (tl eq null) tr else if (tr eq null) tl else if (tl.isRed) { @@ -1129,17 +1129,17 @@ private[collection] object RedBlackTree { def intersect[A, B](t1: Tree[A, B] | Null, t2: Tree[A, B] | Null)(implicit ordering: Ordering[A]): Tree[A, B] | Null = blacken(_intersect(t1, t2)) - def difference[A, B](t1: Tree[A, B] | Null, t2: Tree[A, _] | Null)(implicit ordering: Ordering[A]): Tree[A, B] | Null = + def difference[A, B](t1: Tree[A, B] | Null, t2: Tree[A, ?] | Null)(implicit ordering: Ordering[A]): Tree[A, B] | Null = blacken(_difference(t1, t2.asInstanceOf[Tree[A, B]])) /** Compute the rank from a tree and its black height */ - @`inline` private[this] def rank(t: Tree[_, _] | Null, bh: Int): Int = { + @`inline` private def rank(t: Tree[?, ?] | Null, bh: Int): Int = { if(t eq null) 0 else if(t.isBlack) 2*(bh-1) else 2*bh-1 } - private[this] def joinRight[A, B](tl: Tree[A, B] | Null, k: A, v: B, tr: Tree[A, B] | Null, bhtl: Int, rtr: Int): Tree[A, B] = { + private def joinRight[A, B](tl: Tree[A, B] | Null, k: A, v: B, tr: Tree[A, B] | Null, bhtl: Int, rtr: Int): Tree[A, B] = { val rtl = rank(tl, bhtl) if(rtl == (rtr/2)*2) RedTree(k, v, tl, tr) else { @@ -1155,7 +1155,7 @@ private[collection] object RedBlackTree { } } - private[this] def joinLeft[A, B](tl: Tree[A, B] | Null, k: A, v: B, tr: Tree[A, B] | Null, rtl: Int, bhtr: Int): Tree[A, B] = { + private def joinLeft[A, B](tl: Tree[A, B] | Null, k: A, v: B, tr: Tree[A, B] | Null, rtl: Int, bhtr: Int): Tree[A, B] = { val rtr = rank(tr, bhtr) if(rtr == (rtl/2)*2) RedTree(k, v, tl, tr) else { @@ -1171,8 +1171,8 @@ private[collection] object RedBlackTree { } } - private[this] def join[A, B](tl: Tree[A, B] | Null, k: A, v: B, tr: Tree[A, B] | Null): Tree[A, B] = { - @tailrec def h(t: Tree[_, _] | Null, i: Int): Int = + private def join[A, B](tl: Tree[A, B] | Null, k: A, v: B, tr: Tree[A, B] | Null): Tree[A, B] = { + @tailrec def h(t: Tree[?, ?] | Null, i: Int): Int = if(t eq null) i+1 else h(t.left, if(t.isBlack) i+1 else i) val bhtl = h(tl, 0) val bhtr = h(tr, 0) @@ -1187,7 +1187,7 @@ private[collection] object RedBlackTree { } else mkTree(isRedTree(tl) || isRedTree(tr), k, v, tl, tr) } - private[this] def split[A, B](t: Tree[A, B] | Null, k2: A)(implicit ordering: Ordering[A]): (Tree[A, B] | Null, Tree[A, B] | Null, Tree[A, B] | Null, A) = + private def split[A, B](t: Tree[A, B] | Null, k2: A)(implicit ordering: Ordering[A]): (Tree[A, B] | Null, Tree[A, B] | Null, Tree[A, B] | Null, A) = if(t eq null) (null, null, null, k2) else { val cmp = ordering.compare(k2, t.key) @@ -1201,14 +1201,14 @@ private[collection] object RedBlackTree { } } - private[this] def splitLast[A, B](t: Tree[A, B]): (Tree[A, B], A, B) = + private def splitLast[A, B](t: Tree[A, B]): (Tree[A, B], A, B) = if(t.right eq null) (t.left.nn, t.key, t.value) else { val (tt, kk, vv) = splitLast(t.right.nn) (join(t.left, t.key, t.value, tt), kk, vv) } - private[this] def join2[A, B](tl: Tree[A, B] | Null, tr: Tree[A, B] | Null): Tree[A, B] | Null = + private def join2[A, B](tl: Tree[A, B] | Null, tr: Tree[A, B] | Null): Tree[A, B] | Null = if(tl eq null) tr else if(tr eq null) tl else { @@ -1216,7 +1216,7 @@ private[collection] object RedBlackTree { join(ttl, k, v, tr) } - private[this] def _union[A, B](t1: Tree[A, B] | Null, t2: Tree[A, B] | Null)(implicit ordering: Ordering[A]): Tree[A, B] | Null = + private def _union[A, B](t1: Tree[A, B] | Null, t2: Tree[A, B] | Null)(implicit ordering: Ordering[A]): Tree[A, B] | Null = if((t1 eq null) || (t1 eq t2)) t2 else if(t2 eq null) t1 else { @@ -1226,7 +1226,7 @@ private[collection] object RedBlackTree { join(tl, k1, t2.value, tr) } - private[this] def _intersect[A, B](t1: Tree[A, B] | Null, t2: Tree[A, B] | Null)(implicit ordering: Ordering[A]): Tree[A, B] | Null = + private def _intersect[A, B](t1: Tree[A, B] | Null, t2: Tree[A, B] | Null)(implicit ordering: Ordering[A]): Tree[A, B] | Null = if((t1 eq null) || (t2 eq null)) null else if (t1 eq t2) t1 else { @@ -1237,7 +1237,7 @@ private[collection] object RedBlackTree { else join2(tl, tr) } - private[this] def _difference[A, B](t1: Tree[A, B] | Null, t2: Tree[A, B] | Null)(implicit ordering: Ordering[A]): Tree[A, B] | Null = + private def _difference[A, B](t1: Tree[A, B] | Null, t2: Tree[A, B] | Null)(implicit ordering: Ordering[A]): Tree[A, B] | Null = if((t1 eq null) || (t2 eq null)) t1 else if (t1 eq t2) null else { diff --git a/library/src/scala/collection/immutable/Seq.scala b/library/src/scala/collection/immutable/Seq.scala index f46b6770ac9b..bd10a4380077 100644 --- a/library/src/scala/collection/immutable/Seq.scala +++ b/library/src/scala/collection/immutable/Seq.scala @@ -150,7 +150,7 @@ object LinearSeq extends SeqFactory.Delegate[LinearSeq](List) { } } -transparent trait LinearSeqOps[+A, +CC[X] <: LinearSeq[X], +C <: LinearSeq[A] with LinearSeqOps[A, CC, C]] +transparent trait LinearSeqOps[+A, +CC[X] <: LinearSeq[X], +C <: LinearSeq[A] & LinearSeqOps[A, CC, C]] extends Any with SeqOps[A, CC, C] with collection.LinearSeqOps[A, CC, C] diff --git a/library/src/scala/collection/immutable/SeqMap.scala b/library/src/scala/collection/immutable/SeqMap.scala index fcc706deb792..f6e16449107c 100644 --- a/library/src/scala/collection/immutable/SeqMap.scala +++ b/library/src/scala/collection/immutable/SeqMap.scala @@ -239,9 +239,9 @@ object SeqMap extends MapFactory[SeqMap] { } private final class SeqMapBuilderImpl[K, V] extends ReusableBuilder[(K, V), SeqMap[K, V]] { - private[this] var elems: SeqMap[K, V] = SeqMap.empty - private[this] var switchedToVectorMapBuilder: Boolean = false - private[this] var vectorMapBuilder: VectorMapBuilder[K, V] = _ + private var elems: SeqMap[K, V] = SeqMap.empty + private var switchedToVectorMapBuilder: Boolean = false + private var vectorMapBuilder: VectorMapBuilder[K, V] = compiletime.uninitialized override def clear(): Unit = { elems = SeqMap.empty diff --git a/library/src/scala/collection/immutable/Set.scala b/library/src/scala/collection/immutable/Set.scala index c35189acbc0d..408e8e6d1d6f 100644 --- a/library/src/scala/collection/immutable/Set.scala +++ b/library/src/scala/collection/immutable/Set.scala @@ -141,8 +141,8 @@ object Set extends IterableFactory[Set] { @SerialVersionUID(3L) private abstract class SetNIterator[A](n: Int) extends AbstractIterator[A] with Serializable { - private[this] var current = 0 - private[this] var remainder = n + private var current = 0 + private var remainder = n override def knownSize: Int = remainder def hasNext = remainder > 0 def apply(i: Int): A @@ -363,9 +363,9 @@ abstract class AbstractSet[A] extends scala.collection.AbstractSet[A] with Set[A * $multipleResults */ private final class SetBuilderImpl[A] extends ReusableBuilder[A, Set[A]] { - private[this] var elems: Set[A] = Set.empty - private[this] var switchedToHashSetBuilder: Boolean = false - private[this] var hashSetBuilder: HashSetBuilder[A] = _ + private var elems: Set[A] = Set.empty + private var switchedToHashSetBuilder: Boolean = false + private var hashSetBuilder: HashSetBuilder[A] = compiletime.uninitialized override def clear(): Unit = { elems = Set.empty diff --git a/library/src/scala/collection/immutable/SortedMap.scala b/library/src/scala/collection/immutable/SortedMap.scala index b045c498d3c9..a568e6571f20 100644 --- a/library/src/scala/collection/immutable/SortedMap.scala +++ b/library/src/scala/collection/immutable/SortedMap.scala @@ -86,10 +86,10 @@ trait SortedMap[K, +V] override def withDefaultValue[V1 >: V](d: V1): SortedMap[K, V1] = new SortedMap.WithDefault[K, V1](this, _ => d) } -transparent trait SortedMapOps[K, +V, +CC[X, +Y] <: Map[X, Y] with SortedMapOps[X, Y, CC, _], +C <: SortedMapOps[K, V, CC, C]] +transparent trait SortedMapOps[K, +V, +CC[X, +Y] <: Map[X, Y] & SortedMapOps[X, Y, CC, ?], +C <: SortedMapOps[K, V, CC, C]] extends MapOps[K, V, Map, C] with collection.SortedMapOps[K, V, CC, C] { self => - protected def coll: C with CC[K, V] + protected def coll: C & CC[K, V] def unsorted: Map[K, V] @@ -118,10 +118,10 @@ transparent trait SortedMapOps[K, +V, +CC[X, +Y] <: Map[X, Y] with SortedMapOps[ else coll.updated(key, nextValue) } } - override def transform[W](f: (K, V) => W): CC[K, W] = map({ case (k, v) => (k, f(k, v)) })(ordering) + override def transform[W](f: (K, V) => W): CC[K, W] = map({ case (k, v) => (k, f(k, v)) })(using ordering) } -transparent trait StrictOptimizedSortedMapOps[K, +V, +CC[X, +Y] <: Map[X, Y] with SortedMapOps[X, Y, CC, _], +C <: SortedMapOps[K, V, CC, C]] +transparent trait StrictOptimizedSortedMapOps[K, +V, +CC[X, +Y] <: Map[X, Y] & SortedMapOps[X, Y, CC, ?], +C <: SortedMapOps[K, V, CC, C]] extends SortedMapOps[K, V, CC, C] with collection.StrictOptimizedSortedMapOps[K, V, CC, C] with StrictOptimizedMapOps[K, V, Map, C] { diff --git a/library/src/scala/collection/immutable/Stream.scala b/library/src/scala/collection/immutable/Stream.scala index 941e4ff5d158..05e1bcaf087a 100644 --- a/library/src/scala/collection/immutable/Stream.scala +++ b/library/src/scala/collection/immutable/Stream.scala @@ -49,7 +49,7 @@ sealed abstract class Stream[+A] extends AbstractSeq[A] override def iterableFactory: SeqFactory[Stream] = Stream - override protected[this] def className: String = "Stream" + override protected def className: String = "Stream" /** Apply the given function `f` to each element of this linear sequence * (while respecting the order of the elements). @@ -104,7 +104,7 @@ sealed abstract class Stream[+A] extends AbstractSeq[A] @deprecated("The `append` operation has been renamed `lazyAppendedAll`", "2.13.0") @inline final def append[B >: A](rest: => IterableOnce[B]): Stream[B] = lazyAppendedAll(rest) - protected[this] def writeReplace(): AnyRef = + protected def writeReplace(): AnyRef = if(nonEmpty && tailDefined) new Stream.SerializationProxy[A](this) else this /** Prints elements of this stream one by one, separated by commas. */ @@ -245,7 +245,7 @@ sealed abstract class Stream[+A] extends AbstractSeq[A] sb } - private[this] def addStringNoForce(b: JStringBuilder, start: String, sep: String, end: String): b.type = { + private def addStringNoForce(b: JStringBuilder, start: String, sep: String, end: String): b.type = { b.append(start) if (nonEmpty) { b.append(head) @@ -397,8 +397,8 @@ object Stream extends SeqFactory[Stream] { @SerialVersionUID(3L) final class Cons[A](override val head: A, tl: => Stream[A]) extends Stream[A] { override def isEmpty: Boolean = false - @volatile private[this] var tlVal: Stream[A] = _ - @volatile private[this] var tlGen: (() => Stream[A]) | Null = () => tl + @volatile private var tlVal: Stream[A] = compiletime.uninitialized + @volatile private var tlGen: (() => Stream[A]) | Null = () => tl protected def tailDefined: Boolean = tlGen eq null override def tail: Stream[A] = { if (!tailDefined) @@ -480,9 +480,9 @@ object Stream extends SeqFactory[Stream] { private[immutable] def withFilter[A](l: Stream[A] @uncheckedVariance, p: A => Boolean): collection.WithFilter[A, Stream] = new WithFilter[A](l, p) - private[this] final class WithFilter[A](l: Stream[A] @uncheckedVariance, p: A => Boolean) extends collection.WithFilter[A, Stream] { - private[this] var s: Stream[A] = l // set to null to allow GC after filtered - private[this] lazy val filtered: Stream[A] = { val f = s.filter(p); s = nullForGC[Stream[A]]; f } // don't set to null if throw during filter + private final class WithFilter[A](l: Stream[A] @uncheckedVariance, p: A => Boolean) extends collection.WithFilter[A, Stream] { + private var s: Stream[A] = l // set to null to allow GC after filtered + private lazy val filtered: Stream[A] = { val f = s.filter(p); s = nullForGC[Stream[A]]; f } // don't set to null if throw during filter def map[B](f: A => B): Stream[B] = filtered.map(f) def flatMap[B](f: A => IterableOnce[B]): Stream[B] = filtered.flatMap(f) def foreach[U](f: A => U): Unit = filtered.foreach(f) @@ -544,7 +544,7 @@ object Stream extends SeqFactory[Stream] { @SerialVersionUID(3L) class SerializationProxy[A](@transient protected var coll: Stream[A]) extends Serializable { - private[this] def writeObject(out: ObjectOutputStream): Unit = { + private def writeObject(out: ObjectOutputStream): Unit = { out.defaultWriteObject() var these = coll while(these.nonEmpty && these.tailDefined) { @@ -555,7 +555,7 @@ object Stream extends SeqFactory[Stream] { out.writeObject(these) } - private[this] def readObject(in: ObjectInputStream): Unit = { + private def readObject(in: ObjectInputStream): Unit = { in.defaultReadObject() val init = new ArrayBuffer[A] var initRead = false @@ -567,6 +567,6 @@ object Stream extends SeqFactory[Stream] { coll = (init ++: tail) } - protected[this] def readResolve(): Any = coll + protected def readResolve(): Any = coll } } diff --git a/library/src/scala/collection/immutable/StrictOptimizedSeqOps.scala b/library/src/scala/collection/immutable/StrictOptimizedSeqOps.scala index 6bd8130980d1..19f356cdad82 100644 --- a/library/src/scala/collection/immutable/StrictOptimizedSeqOps.scala +++ b/library/src/scala/collection/immutable/StrictOptimizedSeqOps.scala @@ -82,6 +82,6 @@ transparent trait StrictOptimizedSeqOps[+A, +CC[B] <: caps.Pure, +C] b.result() } - override def sorted[B >: A](implicit ord: Ordering[B]): C = super.sorted(ord) + override def sorted[B >: A](implicit ord: Ordering[B]): C = super.sorted(using ord) } diff --git a/library/src/scala/collection/immutable/TreeMap.scala b/library/src/scala/collection/immutable/TreeMap.scala index 810c01ca2e5f..fcab05a54782 100644 --- a/library/src/scala/collection/immutable/TreeMap.scala +++ b/library/src/scala/collection/immutable/TreeMap.scala @@ -80,10 +80,10 @@ final class TreeMap[K, +V] private (private val tree: RB.Tree[K, V] | Null)(impl with SortedMapFactoryDefaults[K, V, TreeMap, Iterable, Map] with DefaultSerializable { - def this()(implicit ordering: Ordering[K]) = this(null)(ordering) + def this()(implicit ordering: Ordering[K]) = this(null)(using ordering) private[immutable] def tree0: RB.Tree[K, V] | Null = tree - private[this] def newMapOrSelf[V1 >: V](t: RB.Tree[K, V1] | Null): TreeMap[K, V1] = if(t eq tree) this else new TreeMap[K, V1](t) + private def newMapOrSelf[V1 >: V](t: RB.Tree[K, V1] | Null): TreeMap[K, V1] = if(t eq tree) this else new TreeMap[K, V1](t) override def sortedMapFactory: SortedMapFactory[TreeMap] = TreeMap @@ -91,20 +91,20 @@ final class TreeMap[K, +V] private (private val tree: RB.Tree[K, V] | Null)(impl def keysIteratorFrom(start: K): Iterator[K] = RB.keysIterator(tree, Some(start)) - override def keySet: TreeSet[K] = new TreeSet(tree)(ordering) + override def keySet: TreeSet[K] = new TreeSet(tree)(using ordering) def iteratorFrom(start: K): Iterator[(K, V)] = RB.iterator(tree, Some(start)) override def valuesIteratorFrom(start: K): Iterator[V] = RB.valuesIterator(tree, Some(start)) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[(K, V), S]): S with EfficientSplit = + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[(K, V), S]): S & EfficientSplit = shape.parUnbox( scala.collection.convert.impl.AnyBinaryTreeStepper.from[(K, V), RB.Tree[K, V]]( size, tree, _.left, _.right, x => (x.key, x.value) ) ) - override def keyStepper[S <: Stepper[_]](implicit shape: StepperShape[K, S]): S with EfficientSplit = { + override def keyStepper[S <: Stepper[?]](implicit shape: StepperShape[K, S]): S & EfficientSplit = { import scala.collection.convert.impl._ type T = RB.Tree[K, V] val s = shape.shape match { @@ -113,10 +113,10 @@ final class TreeMap[K, +V] private (private val tree: RB.Tree[K, V] | Null)(impl case StepperShape.DoubleShape => DoubleBinaryTreeStepper.from[T](size, tree, _.left, _.right, _.key.asInstanceOf[Double]) case _ => shape.parUnbox(AnyBinaryTreeStepper.from[K, T](size, tree, _.left, _.right, _.key)) } - s.asInstanceOf[S with EfficientSplit] + s.asInstanceOf[S & EfficientSplit] } - override def valueStepper[S <: Stepper[_]](implicit shape: StepperShape[V, S]): S with EfficientSplit = { + override def valueStepper[S <: Stepper[?]](implicit shape: StepperShape[V, S]): S & EfficientSplit = { import scala.collection.convert.impl._ type T = RB.Tree[K, V] val s = shape.shape match { @@ -125,7 +125,7 @@ final class TreeMap[K, +V] private (private val tree: RB.Tree[K, V] | Null)(impl case StepperShape.DoubleShape => DoubleBinaryTreeStepper.from[T] (size, tree, _.left, _.right, _.value.asInstanceOf[Double]) case _ => shape.parUnbox(AnyBinaryTreeStepper.from[V, T] (size, tree, _.left, _.right, _.value.asInstanceOf[V])) } - s.asInstanceOf[S with EfficientSplit] + s.asInstanceOf[S & EfficientSplit] } def get(key: K): Option[V] = RB.get(tree, key) @@ -253,7 +253,7 @@ final class TreeMap[K, +V] private (private val tree: RB.Tree[K, V] | Null)(impl override def takeRight(n: Int): TreeMap[K, V] = drop(size - math.max(n, 0)) - private[this] def countWhile(p: ((K, V)) => Boolean): Int = { + private def countWhile(p: ((K, V)) => Boolean): Int = { var result = 0 val it = iterator while (it.hasNext && p(it.next())) result += 1 @@ -300,7 +300,7 @@ final class TreeMap[K, +V] private (private val tree: RB.Tree[K, V] | Null)(impl case _ => super.equals(obj) } - override protected[this] def className = "TreeMap" + override protected def className = "TreeMap" } /** $factoryInfo @@ -342,7 +342,7 @@ object TreeMap extends SortedMapFactory[TreeMap] { private object adder extends AbstractFunction2[K, V, Unit] { // we cache tree to avoid the outer access to tree // in the hot path (apply) - private[this] var accumulator: Tree | Null = null + private var accumulator: Tree | Null = null def addForEach(hasForEach: collection.Map[K, V]): Unit = { accumulator = tree hasForEach.foreachEntry(this) diff --git a/library/src/scala/collection/immutable/TreeSeqMap.scala b/library/src/scala/collection/immutable/TreeSeqMap.scala index 76e39cbc8c2e..3bb7c3d29f34 100644 --- a/library/src/scala/collection/immutable/TreeSeqMap.scala +++ b/library/src/scala/collection/immutable/TreeSeqMap.scala @@ -59,7 +59,7 @@ final class TreeSeqMap[K, +V] private ( import TreeSeqMap._ - override protected[this] def className: String = "TreeSeqMap" + override protected def className: String = "TreeSeqMap" override def mapFactory: MapFactory[TreeSeqMap] = TreeSeqMap @@ -139,7 +139,7 @@ final class TreeSeqMap[K, +V] private ( def get(key: K): Option[V] = mapping.get(key).map(value) def iterator: Iterator[(K, V)] = new AbstractIterator[(K, V)] { - private[this] val iter = ordering.iterator + private val iter = ordering.iterator override def hasNext: Boolean = iter.hasNext @@ -147,7 +147,7 @@ final class TreeSeqMap[K, +V] private ( } override def keysIterator: Iterator[K] = new AbstractIterator[K] { - private[this] val iter = ordering.iterator + private val iter = ordering.iterator override def hasNext: Boolean = iter.hasNext @@ -155,7 +155,7 @@ final class TreeSeqMap[K, +V] private ( } override def valuesIterator: Iterator[V] = new AbstractIterator[V] { - private[this] val iter = ordering.iterator + private val iter = ordering.iterator override def hasNext: Boolean = iter.hasNext @@ -286,8 +286,8 @@ final class TreeSeqMap[K, +V] private ( new TreeSeqMap[K, V2](ong, mng, ord, orderedBy) } - @`inline` private[this] def value(p: (_, V)) = p._2 - @`inline` private[this] def binding(k: K) = mapping(k).copy(_1 = k) + @`inline` private def value(p: (?, V)) = p._2 + @`inline` private def binding(k: K) = mapping(k).copy(_1 = k) } object TreeSeqMap extends MapFactory[TreeSeqMap] { sealed trait OrderBy @@ -317,11 +317,11 @@ object TreeSeqMap extends MapFactory[TreeSeqMap] { def newBuilder[K, V](orderedBy: OrderBy): mutable.Builder[(K, V), TreeSeqMap[K, V]] = new Builder[K, V](orderedBy) final class Builder[K, V](orderedBy: OrderBy) extends mutable.Builder[(K, V), TreeSeqMap[K, V]] { - private[this] val bdr = new MapBuilderImpl[K, (Int, V)] - private[this] var ong = Ordering.empty[K] - private[this] var ord = 0 + private val bdr = new MapBuilderImpl[K, (Int, V)] + private var ong = Ordering.empty[K] + private var ord = 0 @annotation.stableNull - private[this] var aliased: TreeSeqMap[K, V] | Null = null + private var aliased: TreeSeqMap[K, V] | Null = null override def addOne(elem: (K, V)): this.type = addOne(elem._1, elem._2) def addOne(key: K, value: V): this.type = { @@ -381,15 +381,15 @@ object TreeSeqMap extends MapFactory[TreeSeqMap] { // because we know that Ints are at least 32 bits we can have at most 32 Bins and // one Tip sitting on the tree at any point. Therefore we know the maximum stack // depth is 33 - private[this] var index = 0 - private[this] val buffer = new Array[AnyRef](33) + private var index = 0 + private val buffer = new Array[AnyRef](33) - private[this] def pop = { + private def pop = { index -= 1 buffer(index).asInstanceOf[Ordering[V]] } - private[this] def push[V2 >: V](x: Ordering[V2]): Unit = { + private def push[V2 >: V](x: Ordering[V2]): Unit = { buffer(index) = x.asInstanceOf[AnyRef] index += 1 } diff --git a/library/src/scala/collection/immutable/TreeSet.scala b/library/src/scala/collection/immutable/TreeSet.scala index 6b1a5561935d..f8622b8b0711 100644 --- a/library/src/scala/collection/immutable/TreeSet.scala +++ b/library/src/scala/collection/immutable/TreeSet.scala @@ -49,11 +49,11 @@ final class TreeSet[A] private[immutable] (private[immutable] val tree: RB.Tree[ if (ordering eq null) throw new NullPointerException("ordering must not be null") - def this()(implicit ordering: Ordering[A]) = this(null)(ordering) + def this()(implicit ordering: Ordering[A]) = this(null)(using ordering) override def sortedIterableFactory: TreeSet.type = TreeSet - private[this] def newSetOrSelf(t: RB.Tree[A, Any] | Null) = if(t eq tree) this else new TreeSet[A](t) + private def newSetOrSelf(t: RB.Tree[A, Any] | Null) = if(t eq tree) this else new TreeSet[A](t) override def size: Int = RB.count(tree) @@ -71,7 +71,7 @@ final class TreeSet[A] private[immutable] (private[immutable] val tree: RB.Tree[ if ((ord eq ordering) && nonEmpty) { head } else { - super.min(ord) + super.min(using ord) } } @@ -79,7 +79,7 @@ final class TreeSet[A] private[immutable] (private[immutable] val tree: RB.Tree[ if ((ord eq ordering) && nonEmpty) { last } else { - super.max(ord) + super.max(using ord) } } @@ -106,7 +106,7 @@ final class TreeSet[A] private[immutable] (private[immutable] val tree: RB.Tree[ override def takeRight(n: Int): TreeSet[A] = drop(size - math.max(n, 0)) - private[this] def countWhile(p: A => Boolean): Int = { + private def countWhile(p: A => Boolean): Int = { var result = 0 val it = iterator while (it.hasNext && p(it.next())) result += 1 @@ -134,7 +134,7 @@ final class TreeSet[A] private[immutable] (private[immutable] val tree: RB.Tree[ def iteratorFrom(start: A): Iterator[A] = RB.keysIterator(tree, Some(start)) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[A, S]): S with EfficientSplit = { + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[A, S]): S & EfficientSplit = { import scala.collection.convert.impl._ type T = RB.Tree[A, Any] val s = shape.shape match { @@ -143,7 +143,7 @@ final class TreeSet[A] private[immutable] (private[immutable] val tree: RB.Tree[ case StepperShape.DoubleShape => DoubleBinaryTreeStepper.from[T](size, tree, _.left, _.right, _.key.asInstanceOf[Double]) case _ => shape.parUnbox(AnyBinaryTreeStepper.from[A, T](size, tree, _.left, _.right, _.key)) } - s.asInstanceOf[S with EfficientSplit] + s.asInstanceOf[S & EfficientSplit] } /** Checks if this set contains element `elem`. @@ -228,7 +228,7 @@ final class TreeSet[A] private[immutable] (private[immutable] val tree: RB.Tree[ case _ => super.equals(obj) } - override protected[this] def className = "TreeSet" + override protected def className = "TreeSet" } /** @@ -265,7 +265,7 @@ object TreeSet extends SortedIterableFactory[TreeSet] { extends RB.SetHelper[A] with ReusableBuilder[A, TreeSet[A]] { type Tree = RB.Tree[A, Any] - private [this] var tree:RB.Tree[A, Any] | Null = null + private var tree:RB.Tree[A, Any] | Null = null override def addOne(elem: A): this.type = { tree = mutableUpd(tree, elem) @@ -280,10 +280,10 @@ object TreeSet extends SortedIterableFactory[TreeSet] { // calling `beforePublish` makes `tree` immutable case ts: TreeSet[A] if ts.ordering == ordering => if (tree eq null) tree = ts.tree - else tree = RB.union(beforePublish(tree), ts.tree)(ordering) + else tree = RB.union(beforePublish(tree), ts.tree)(using ordering) case ts: TreeMap[A @unchecked, _] if ts.ordering == ordering => if (tree eq null) tree = ts.tree0 - else tree = RB.union(beforePublish(tree), ts.tree0)(ordering) + else tree = RB.union(beforePublish(tree), ts.tree0)(using ordering) case _ => super.addAll(xs) } @@ -294,6 +294,6 @@ object TreeSet extends SortedIterableFactory[TreeSet] { tree = null } - override def result(): TreeSet[A] = new TreeSet[A](beforePublish(tree))(ordering) + override def result(): TreeSet[A] = new TreeSet[A](beforePublish(tree))(using ordering) } } diff --git a/library/src/scala/collection/immutable/Vector.scala b/library/src/scala/collection/immutable/Vector.scala index 3af7c7d6a9be..25e2270874dc 100644 --- a/library/src/scala/collection/immutable/Vector.scala +++ b/library/src/scala/collection/immutable/Vector.scala @@ -127,7 +127,7 @@ sealed abstract class Vector[+A] private[immutable] (private[immutable] final va override def iterableFactory: SeqFactory[Vector] = Vector override final def length: Int = - if(this.isInstanceOf[BigVector[_]]) this.asInstanceOf[BigVector[_]].length0 + if(this.isInstanceOf[BigVector[?]]) this.asInstanceOf[BigVector[?]].length0 else prefix1.length override final def iterator: Iterator[A] = @@ -151,7 +151,7 @@ sealed abstract class Vector[+A] private[immutable] (private[immutable] final va } val newLen = i + java.lang.Integer.bitCount(bitmap) - if(this.isInstanceOf[BigVector[_]]) { + if(this.isInstanceOf[BigVector[?]]) { val b = new VectorBuilder[A] var k = 0 while(k < i) { @@ -185,7 +185,7 @@ sealed abstract class Vector[+A] private[immutable] (private[immutable] final va } i += 1 } - if(this.isInstanceOf[BigVector[_]]) { + if(this.isInstanceOf[BigVector[?]]) { val b = new VectorBuilder[A] b.initFrom(prefix1) this.asInstanceOf[BigVector[A]].foreachRest { v => if(pred(v) != isFlipped) b.addOne(v) } @@ -211,7 +211,7 @@ sealed abstract class Vector[+A] private[immutable] (private[immutable] final va else appendedAll0(suffix, k) } - protected[this] def prependedAll0[B >: A](prefix: collection.IterableOnce[B]^, k: Int): Vector[B] = { + protected def prependedAll0[B >: A](prefix: collection.IterableOnce[B]^, k: Int): Vector[B] = { // k >= 0, k = prefix.knownSize val tinyAppendLimit = 4 + vectorSliceCount if (k < tinyAppendLimit /*|| k < (this.size >>> Log2ConcatFaster)*/) { @@ -219,7 +219,7 @@ sealed abstract class Vector[+A] private[immutable] (private[immutable] final va val it = IndexedSeq.from(prefix).reverseIterator while (it.hasNext) v = it.next() +: v v - } else if (this.size < (k >>> Log2ConcatFaster) && prefix.isInstanceOf[Vector[_]]) { + } else if (this.size < (k >>> Log2ConcatFaster) && prefix.isInstanceOf[Vector[?]]) { var v = prefix.asInstanceOf[Vector[B]] val it = this.iterator while (it.hasNext) v = v :+ it.next() @@ -229,7 +229,7 @@ sealed abstract class Vector[+A] private[immutable] (private[immutable] final va } else super.prependedAll(prefix) } - protected[this] def appendedAll0[B >: A](suffix: collection.IterableOnce[B]^, k: Int): Vector[B] = { + protected def appendedAll0[B >: A](suffix: collection.IterableOnce[B]^, k: Int): Vector[B] = { // k >= 0, k = suffix.knownSize val tinyAppendLimit = 4 + vectorSliceCount if (k < tinyAppendLimit) { @@ -239,12 +239,12 @@ sealed abstract class Vector[+A] private[immutable] (private[immutable] final va case _ => suffix.iterator.foreach(x => v = v.appended(x)) } v - } else if (this.size < (k >>> Log2ConcatFaster) && suffix.isInstanceOf[Vector[_]]) { + } else if (this.size < (k >>> Log2ConcatFaster) && suffix.isInstanceOf[Vector[?]]) { var v = suffix.asInstanceOf[Vector[B]] val ri = this.reverseIterator while (ri.hasNext) v = v.prepended(ri.next()) v - } else if (this.size < k - AlignToFaster && suffix.isInstanceOf[Vector[_]]) { + } else if (this.size < k - AlignToFaster && suffix.isInstanceOf[Vector[?]]) { val v = suffix.asInstanceOf[Vector[B]] new VectorBuilder[B].alignTo(this.size, v).addAll(this).addAll(v).result() } else new VectorBuilder[B].initFrom(this).addAll(suffix).result() @@ -260,12 +260,12 @@ sealed abstract class Vector[+A] private[immutable] (private[immutable] final va override def init: Vector[A] = slice(0, length-1) /** Like slice but parameters must be 0 <= lo < hi < length */ - protected[this] def slice0(lo: Int, hi: Int): Vector[A] + protected def slice0(lo: Int, hi: Int): Vector[A] /** Number of slices */ protected[immutable] def vectorSliceCount: Int /** Slice at index */ - protected[immutable] def vectorSlice(idx: Int): Array[_ <: AnyRef | Null] + protected[immutable] def vectorSlice(idx: Int): Array[? <: AnyRef | Null] /** Length of all slices up to and including index */ protected[immutable] def vectorSlicePrefixLength(idx: Int): Int @@ -275,17 +275,17 @@ sealed abstract class Vector[+A] private[immutable] (private[immutable] final va override protected def applyPreferredMaxLength: Int = Vector.defaultApplyPreferredMaxLength - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[A, S]): S with EfficientSplit = { + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[A, S]): S & EfficientSplit = { val s = shape.shape match { case StepperShape.IntShape => new IntVectorStepper(iterator.asInstanceOf[NewVectorIterator[Int]]) case StepperShape.LongShape => new LongVectorStepper(iterator.asInstanceOf[NewVectorIterator[Long]]) case StepperShape.DoubleShape => new DoubleVectorStepper(iterator.asInstanceOf[NewVectorIterator[Double]]) case _ => shape.parUnbox(new AnyVectorStepper[A](iterator.asInstanceOf[NewVectorIterator[A]])) } - s.asInstanceOf[S with EfficientSplit] + s.asInstanceOf[S & EfficientSplit] } - protected[this] def ioob(index: Int): IndexOutOfBoundsException = + protected def ioob(index: Int): IndexOutOfBoundsException = CommonErrors.indexOutOfBounds(index = index, max = length - 1) override final def head: A = @@ -293,8 +293,8 @@ sealed abstract class Vector[+A] private[immutable] (private[immutable] final va else prefix1(0).asInstanceOf[A] override final def last: A = { - if(this.isInstanceOf[BigVector[_]]) { - val suffix = this.asInstanceOf[BigVector[_]].suffix1 + if(this.isInstanceOf[BigVector[?]]) { + val suffix = this.asInstanceOf[BigVector[?]].suffix1 if(suffix.length == 0) throw new NoSuchElementException("empty.tail") else suffix(suffix.length-1) } else prefix1(prefix1.length-1) @@ -361,10 +361,10 @@ private object Vector0 extends BigVector[Nothing](empty1, empty1, 0) { override def init: Vector[Nothing] = throw new UnsupportedOperationException("empty.init") - protected[this] def slice0(lo: Int, hi: Int): Vector[Nothing] = this + protected def slice0(lo: Int, hi: Int): Vector[Nothing] = this protected[immutable] def vectorSliceCount: Int = 0 - protected[immutable] def vectorSlice(idx: Int): Array[_ <: AnyRef | Null] = null.asInstanceOf[Array[_ <: AnyRef | Null]] + protected[immutable] def vectorSlice(idx: Int): Array[? <: AnyRef | Null] = null.asInstanceOf[Array[? <: AnyRef | Null]] protected[immutable] def vectorSlicePrefixLength(idx: Int): Int = 0 override def equals(o: Any): Boolean = { @@ -375,13 +375,13 @@ private object Vector0 extends BigVector[Nothing](empty1, empty1, 0) { } } - override protected[this]def prependedAll0[B >: Nothing](prefix: collection.IterableOnce[B]^, k: Int): Vector[B] = + override protected def prependedAll0[B >: Nothing](prefix: collection.IterableOnce[B]^, k: Int): Vector[B] = Vector.from(prefix) - override protected[this]def appendedAll0[B >: Nothing](suffix: collection.IterableOnce[B]^, k: Int): Vector[B] = + override protected def appendedAll0[B >: Nothing](suffix: collection.IterableOnce[B]^, k: Int): Vector[B] = Vector.from(suffix) - override protected[this] def ioob(index: Int): IndexOutOfBoundsException = + override protected def ioob(index: Int): IndexOutOfBoundsException = new IndexOutOfBoundsException(s"$index is out of bounds (empty vector)") } @@ -414,7 +414,7 @@ private final class Vector1[+A](_data1: Arr1) extends VectorImpl[A](_data1) { override def map[B](f: A => B): Vector[B] = new Vector1(mapElems1(prefix1, f)) - protected[this] def slice0(lo: Int, hi: Int): Vector[A] = + protected def slice0(lo: Int, hi: Int): Vector[A] = new Vector1(copyOfRange(prefix1, lo, hi)) override def tail: Vector[A] = @@ -426,16 +426,16 @@ private final class Vector1[+A](_data1: Arr1) extends VectorImpl[A](_data1) { else new Vector1(copyInit(prefix1)) protected[immutable] def vectorSliceCount: Int = 1 - protected[immutable] def vectorSlice(idx: Int): Array[_ <: AnyRef | Null] = prefix1 + protected[immutable] def vectorSlice(idx: Int): Array[? <: AnyRef | Null] = prefix1 protected[immutable] def vectorSlicePrefixLength(idx: Int): Int = prefix1.length - override protected[this] def prependedAll0[B >: A](prefix: collection.IterableOnce[B]^, k: Int): Vector[B] = + override protected def prependedAll0[B >: A](prefix: collection.IterableOnce[B]^, k: Int): Vector[B] = prepend1IfSpace(prefix1, prefix) match { case null => super.prependedAll0(prefix, k) case data1b => new Vector1(data1b) } - override protected[this] def appendedAll0[B >: A](suffix: collection.IterableOnce[B]^, k: Int): Vector[B] = { + override protected def appendedAll0[B >: A](suffix: collection.IterableOnce[B]^, k: Int): Vector[B] = { val data1b = append1IfSpace(prefix1, suffix) if(data1b ne null) new Vector1(data1b) else super.appendedAll0(suffix, k) @@ -449,7 +449,7 @@ private final class Vector2[+A](_prefix1: Arr1, private[immutable] val len1: Int _suffix1: Arr1, _length0: Int) extends BigVector[A](_prefix1, _suffix1, _length0) { - @inline private[this] def copy(prefix1: Arr1 = prefix1, len1: Int = len1, + @inline private def copy(prefix1: Arr1 = prefix1, len1: Int = len1, data2: Arr2 = data2, suffix1: Arr1 = suffix1, length0: Int = length0) = @@ -496,7 +496,7 @@ private final class Vector2[+A](_prefix1: Arr1, private[immutable] val len1: Int override def map[B](f: A => B): Vector[B] = copy(prefix1 = mapElems1(prefix1, f), data2 = mapElems(2, data2, f), suffix1 = mapElems1(suffix1, f)) - protected[this] def slice0(lo: Int, hi: Int): Vector[A] = { + protected def slice0(lo: Int, hi: Int): Vector[A] = { val b = new VectorSliceBuilder(lo, hi) b.consider(1, prefix1) b.consider(2, data2) @@ -513,7 +513,7 @@ private final class Vector2[+A](_prefix1: Arr1, private[immutable] val len1: Int else slice0(0, length0-1) protected[immutable] def vectorSliceCount: Int = 3 - protected[immutable] def vectorSlice(idx: Int): Array[_ <: AnyRef | Null] = (idx: @switch) match { + protected[immutable] def vectorSlice(idx: Int): Array[? <: AnyRef | Null] = (idx: @switch) match { case 0 => prefix1 case 1 => data2 case 2 => suffix1 @@ -524,7 +524,7 @@ private final class Vector2[+A](_prefix1: Arr1, private[immutable] val len1: Int case 2 => length0 } - override protected[this] def prependedAll0[B >: A](prefix: collection.IterableOnce[B]^, k: Int): Vector[B] = + override protected def prependedAll0[B >: A](prefix: collection.IterableOnce[B]^, k: Int): Vector[B] = prepend1IfSpace(prefix1, prefix) match { case null => super.prependedAll0(prefix, k) case prefix1b => @@ -535,7 +535,7 @@ private final class Vector2[+A](_prefix1: Arr1, private[immutable] val len1: Int ) } - override protected[this] def appendedAll0[B >: A](suffix: collection.IterableOnce[B]^, k: Int): Vector[B] = { + override protected def appendedAll0[B >: A](suffix: collection.IterableOnce[B]^, k: Int): Vector[B] = { val suffix1b = append1IfSpace(suffix1, suffix) if(suffix1b ne null) copy(suffix1 = suffix1b, length0 = length0-suffix1.length+suffix1b.length) else super.appendedAll0(suffix, k) @@ -550,7 +550,7 @@ private final class Vector3[+A](_prefix1: Arr1, private[immutable] val len1: Int private[immutable] val suffix2: Arr2, _suffix1: Arr1, _length0: Int) extends BigVector[A](_prefix1, _suffix1, _length0) { - @inline private[this] def copy(prefix1: Arr1 = prefix1, len1: Int = len1, + @inline private def copy(prefix1: Arr1 = prefix1, len1: Int = len1, prefix2: Arr2 = prefix2, len12: Int = len12, data3: Arr3 = data3, suffix2: Arr2 = suffix2, suffix1: Arr1 = suffix1, @@ -612,7 +612,7 @@ private final class Vector3[+A](_prefix1: Arr1, private[immutable] val len1: Int data3 = mapElems(3, data3, f), suffix2 = mapElems(2, suffix2, f), suffix1 = mapElems1(suffix1, f)) - protected[this] def slice0(lo: Int, hi: Int): Vector[A] = { + protected def slice0(lo: Int, hi: Int): Vector[A] = { val b = new VectorSliceBuilder(lo, hi) b.consider(1, prefix1) b.consider(2, prefix2) @@ -631,7 +631,7 @@ private final class Vector3[+A](_prefix1: Arr1, private[immutable] val len1: Int else slice0(0, length0-1) protected[immutable] def vectorSliceCount: Int = 5 - protected[immutable] def vectorSlice(idx: Int): Array[_ <: AnyRef | Null] = (idx: @switch) match { + protected[immutable] def vectorSlice(idx: Int): Array[? <: AnyRef | Null] = (idx: @switch) match { case 0 => prefix1 case 1 => prefix2 case 2 => data3 @@ -646,7 +646,7 @@ private final class Vector3[+A](_prefix1: Arr1, private[immutable] val len1: Int case 4 => length0 } - override protected[this] def prependedAll0[B >: A](prefix: collection.IterableOnce[B]^, k: Int): Vector[B] = + override protected def prependedAll0[B >: A](prefix: collection.IterableOnce[B]^, k: Int): Vector[B] = prepend1IfSpace(prefix1, prefix) match { case null => super.prependedAll0(prefix, k) case prefix1b => @@ -658,7 +658,7 @@ private final class Vector3[+A](_prefix1: Arr1, private[immutable] val len1: Int ) } - override protected[this] def appendedAll0[B >: A](suffix: collection.IterableOnce[B]^, k: Int): Vector[B] = { + override protected def appendedAll0[B >: A](suffix: collection.IterableOnce[B]^, k: Int): Vector[B] = { val suffix1b = append1IfSpace(suffix1, suffix) if(suffix1b ne null) copy(suffix1 = suffix1b, length0 = length0-suffix1.length+suffix1b.length) else super.appendedAll0(suffix, k) @@ -674,7 +674,7 @@ private final class Vector4[+A](_prefix1: Arr1, private[immutable] val len1: Int private[immutable] val suffix3: Arr3, private[immutable] val suffix2: Arr2, _suffix1: Arr1, _length0: Int) extends BigVector[A](_prefix1, _suffix1, _length0) { - @inline private[this] def copy(prefix1: Arr1 = prefix1, len1: Int = len1, + @inline private def copy(prefix1: Arr1 = prefix1, len1: Int = len1, prefix2: Arr2 = prefix2, len12: Int = len12, prefix3: Arr3 = prefix3, len123: Int = len123, data4: Arr4 = data4, @@ -749,7 +749,7 @@ private final class Vector4[+A](_prefix1: Arr1, private[immutable] val len1: Int data4 = mapElems(4, data4, f), suffix3 = mapElems(3, suffix3, f), suffix2 = mapElems(2, suffix2, f), suffix1 = mapElems1(suffix1, f)) - protected[this] def slice0(lo: Int, hi: Int): Vector[A] = { + protected def slice0(lo: Int, hi: Int): Vector[A] = { val b = new VectorSliceBuilder(lo, hi) b.consider(1, prefix1) b.consider(2, prefix2) @@ -770,7 +770,7 @@ private final class Vector4[+A](_prefix1: Arr1, private[immutable] val len1: Int else slice0(0, length0-1) protected[immutable] def vectorSliceCount: Int = 7 - protected[immutable] def vectorSlice(idx: Int): Array[_ <: AnyRef | Null] = (idx: @switch) match { + protected[immutable] def vectorSlice(idx: Int): Array[? <: AnyRef | Null] = (idx: @switch) match { case 0 => prefix1 case 1 => prefix2 case 2 => prefix3 @@ -789,7 +789,7 @@ private final class Vector4[+A](_prefix1: Arr1, private[immutable] val len1: Int case 6 => length0 } - override protected[this] def prependedAll0[B >: A](prefix: collection.IterableOnce[B]^, k: Int): Vector[B] = + override protected def prependedAll0[B >: A](prefix: collection.IterableOnce[B]^, k: Int): Vector[B] = prepend1IfSpace(prefix1, prefix) match { case null => super.prependedAll0(prefix, k) case prefix1b => @@ -802,7 +802,7 @@ private final class Vector4[+A](_prefix1: Arr1, private[immutable] val len1: Int ) } - override protected[this] def appendedAll0[B >: A](suffix: collection.IterableOnce[B]^, k: Int): Vector[B] = { + override protected def appendedAll0[B >: A](suffix: collection.IterableOnce[B]^, k: Int): Vector[B] = { val suffix1b = append1IfSpace(suffix1, suffix) if(suffix1b ne null) copy(suffix1 = suffix1b, length0 = length0-suffix1.length+suffix1b.length) else super.appendedAll0(suffix, k) @@ -819,7 +819,7 @@ private final class Vector5[+A](_prefix1: Arr1, private[immutable] val len1: Int private[immutable] val suffix4: Arr4, private[immutable] val suffix3: Arr3, private[immutable] val suffix2: Arr2, _suffix1: Arr1, _length0: Int) extends BigVector[A](_prefix1, _suffix1, _length0) { - @inline private[this] def copy(prefix1: Arr1 = prefix1, len1: Int = len1, + @inline private def copy(prefix1: Arr1 = prefix1, len1: Int = len1, prefix2: Arr2 = prefix2, len12: Int = len12, prefix3: Arr3 = prefix3, len123: Int = len123, prefix4: Arr4 = prefix4, len1234: Int = len1234, @@ -907,7 +907,7 @@ private final class Vector5[+A](_prefix1: Arr1, private[immutable] val len1: Int data5 = mapElems(5, data5, f), suffix4 = mapElems(4, suffix4, f), suffix3 = mapElems(3, suffix3, f), suffix2 = mapElems(2, suffix2, f), suffix1 = mapElems1(suffix1, f)) - protected[this] def slice0(lo: Int, hi: Int): Vector[A] = { + protected def slice0(lo: Int, hi: Int): Vector[A] = { val b = new VectorSliceBuilder(lo, hi) b.consider(1, prefix1) b.consider(2, prefix2) @@ -930,7 +930,7 @@ private final class Vector5[+A](_prefix1: Arr1, private[immutable] val len1: Int else slice0(0, length0-1) protected[immutable] def vectorSliceCount: Int = 9 - protected[immutable] def vectorSlice(idx: Int): Array[_ <: AnyRef | Null] = (idx: @switch) match { + protected[immutable] def vectorSlice(idx: Int): Array[? <: AnyRef | Null] = (idx: @switch) match { case 0 => prefix1 case 1 => prefix2 case 2 => prefix3 @@ -953,7 +953,7 @@ private final class Vector5[+A](_prefix1: Arr1, private[immutable] val len1: Int case 8 => length0 } - override protected[this] def prependedAll0[B >: A](prefix: collection.IterableOnce[B]^, k: Int): Vector[B] = + override protected def prependedAll0[B >: A](prefix: collection.IterableOnce[B]^, k: Int): Vector[B] = prepend1IfSpace(prefix1, prefix) match { case null => super.prependedAll0(prefix, k) case prefix1b => @@ -967,7 +967,7 @@ private final class Vector5[+A](_prefix1: Arr1, private[immutable] val len1: Int ) } - override protected[this] def appendedAll0[B >: A](suffix: collection.IterableOnce[B]^, k: Int): Vector[B] = { + override protected def appendedAll0[B >: A](suffix: collection.IterableOnce[B]^, k: Int): Vector[B] = { val suffix1b = append1IfSpace(suffix1, suffix) if(suffix1b ne null) copy(suffix1 = suffix1b, length0 = length0-suffix1.length+suffix1b.length) else super.appendedAll0(suffix, k) @@ -985,7 +985,7 @@ private final class Vector6[+A](_prefix1: Arr1, private[immutable] val len1: Int private[immutable] val suffix5: Arr5, private[immutable] val suffix4: Arr4, private[immutable] val suffix3: Arr3, private[immutable] val suffix2: Arr2, _suffix1: Arr1, _length0: Int) extends BigVector[A](_prefix1, _suffix1, _length0) { - @inline private[this] def copy(prefix1: Arr1 = prefix1, len1: Int = len1, + @inline private def copy(prefix1: Arr1 = prefix1, len1: Int = len1, prefix2: Arr2 = prefix2, len12: Int = len12, prefix3: Arr3 = prefix3, len123: Int = len123, prefix4: Arr4 = prefix4, len1234: Int = len1234, @@ -1086,7 +1086,7 @@ private final class Vector6[+A](_prefix1: Arr1, private[immutable] val len1: Int data6 = mapElems(6, data6, f), suffix5 = mapElems(5, suffix5, f), suffix4 = mapElems(4, suffix4, f), suffix3 = mapElems(3, suffix3, f), suffix2 = mapElems(2, suffix2, f), suffix1 = mapElems1(suffix1, f)) - protected[this] def slice0(lo: Int, hi: Int): Vector[A] = { + protected def slice0(lo: Int, hi: Int): Vector[A] = { val b = new VectorSliceBuilder(lo, hi) b.consider(1, prefix1) b.consider(2, prefix2) @@ -1111,7 +1111,7 @@ private final class Vector6[+A](_prefix1: Arr1, private[immutable] val len1: Int else slice0(0, length0-1) protected[immutable] def vectorSliceCount: Int = 11 - protected[immutable] def vectorSlice(idx: Int): Array[_ <: AnyRef | Null] = (idx: @switch) match { + protected[immutable] def vectorSlice(idx: Int): Array[? <: AnyRef | Null] = (idx: @switch) match { case 0 => prefix1 case 1 => prefix2 case 2 => prefix3 @@ -1138,7 +1138,7 @@ private final class Vector6[+A](_prefix1: Arr1, private[immutable] val len1: Int case 10 => length0 } - override protected[this] def prependedAll0[B >: A](prefix: collection.IterableOnce[B]^, k: Int): Vector[B] = + override protected def prependedAll0[B >: A](prefix: collection.IterableOnce[B]^, k: Int): Vector[B] = prepend1IfSpace(prefix1, prefix) match { case null => super.prependedAll0(prefix, k) case prefix1b => @@ -1153,7 +1153,7 @@ private final class Vector6[+A](_prefix1: Arr1, private[immutable] val len1: Int ) } - override protected[this] def appendedAll0[B >: A](suffix: collection.IterableOnce[B]^, k: Int): Vector[B] = { + override protected def appendedAll0[B >: A](suffix: collection.IterableOnce[B]^, k: Int): Vector[B] = { val suffix1b = append1IfSpace(suffix1, suffix) if(suffix1b ne null) copy(suffix1 = suffix1b, length0 = length0-suffix1.length+suffix1b.length) else super.appendedAll0(suffix, k) @@ -1170,11 +1170,11 @@ private final class Vector6[+A](_prefix1: Arr1, private[immutable] val len1: Int private final class VectorSliceBuilder(lo: Int, hi: Int) { //println(s"***** VectorSliceBuilder($lo, $hi)") - private[this] val slices = new Array[Array[AnyRef] | Null](11) - private[this] var len, pos, maxDim = 0 + private val slices = new Array[Array[AnyRef] | Null](11) + private var len, pos, maxDim = 0 - @inline private[this] def prefixIdx(n: Int) = n-1 - @inline private[this] def suffixIdx(n: Int) = 11-n + @inline private def prefixIdx(n: Int) = n-1 + @inline private def suffixIdx(n: Int) = 11-n def consider[T <: AnyRef](n: Int, a: Array[T]): Unit = { //println(s"***** consider($n, /${a.length})") @@ -1188,7 +1188,7 @@ private final class VectorSliceBuilder(lo: Int, hi: Int) { pos += count } - private[this] def addSlice[T <: AnyRef](n: Int, a: Array[T], lo: Int, hi: Int): Unit = { + private def addSlice[T <: AnyRef](n: Int, a: Array[T], lo: Int, hi: Int): Unit = { //println(s"***** addSlice($n, /${a.length}, $lo, $hi)") if(n == 1) { add(1, copyOrUse(a, lo, hi)) @@ -1223,7 +1223,7 @@ private final class VectorSliceBuilder(lo: Int, hi: Int) { } } - private[this] def add[T <: AnyRef](n: Int, a: Array[T]): Unit = { + private def add[T <: AnyRef](n: Int, a: Array[T]): Unit = { //println(s"***** add($n, /${a.length})") val idx = if(n <= maxDim) suffixIdx(n) @@ -1329,17 +1329,17 @@ private final class VectorSliceBuilder(lo: Int, hi: Int) { } } - @inline private[this] def prefixOr[T <: AnyRef](n: Int, a: Array[T]): Array[T] = { + @inline private def prefixOr[T <: AnyRef](n: Int, a: Array[T]): Array[T] = { val p = slices(prefixIdx(n)) if(p ne null) p.asInstanceOf[Array[T]] else a } - @inline private[this] def suffixOr[T <: AnyRef](n: Int, a: Array[T]): Array[T] = { + @inline private def suffixOr[T <: AnyRef](n: Int, a: Array[T]): Array[T] = { val s = slices(suffixIdx(n)) if(s ne null) s.asInstanceOf[Array[T]] else a } - @inline private[this] def dataOr[T <: AnyRef](n: Int, a: Array[T]): Array[T] = { + @inline private def dataOr[T <: AnyRef](n: Int, a: Array[T]): Array[T] = { val p = slices(prefixIdx(n)) if(p ne null) p.asInstanceOf[Array[T]] else { @@ -1349,7 +1349,7 @@ private final class VectorSliceBuilder(lo: Int, hi: Int) { } /** Ensure prefix is not empty */ - private[this] def balancePrefix(n: Int): Unit = { + private def balancePrefix(n: Int): Unit = { if(slices(prefixIdx(n)) eq null) { if(n == maxDim) { slices(prefixIdx(n)) = slices(suffixIdx(n)) @@ -1370,7 +1370,7 @@ private final class VectorSliceBuilder(lo: Int, hi: Int) { } /** Ensure suffix is not empty */ - private[this] def balanceSuffix(n: Int): Unit = { + private def balanceSuffix(n: Int): Unit = { if(slices(suffixIdx(n)) eq null) { if(n == maxDim) { slices(suffixIdx(n)) = slices(prefixIdx(n)) @@ -1399,17 +1399,17 @@ private final class VectorSliceBuilder(lo: Int, hi: Int) { final class VectorBuilder[A] extends ReusableBuilder[A, Vector[A]] { - private[this] var a6: Arr6 = _ - private[this] var a5: Arr5 = _ - private[this] var a4: Arr4 = _ - private[this] var a3: Arr3 = _ - private[this] var a2: Arr2 = _ - private[this] var a1: Arr1 = new Arr1(WIDTH) - private[this] var len1, lenRest, offset = 0 - private[this] var prefixIsRightAligned = false - private[this] var depth = 1 - - @inline private[this] final def setLen(i: Int): Unit = { + private var a6: Arr6 = compiletime.uninitialized + private var a5: Arr5 = compiletime.uninitialized + private var a4: Arr4 = compiletime.uninitialized + private var a3: Arr3 = compiletime.uninitialized + private var a2: Arr2 = compiletime.uninitialized + private var a1: Arr1 = new Arr1(WIDTH) + private var len1, lenRest, offset = 0 + private var prefixIsRightAligned = false + private var depth = 1 + + @inline private final def setLen(i: Int): Unit = { len1 = i & MASK lenRest = i - len1 } @@ -1471,16 +1471,16 @@ final class VectorBuilder[A] extends ReusableBuilder[A, Vector[A]] { } } - private[immutable] def initFrom(v: Vector[_]): this.type = { + private[immutable] def initFrom(v: Vector[?]): this.type = { (v.vectorSliceCount: @switch) match { case 0 => case 1 => - val v1 = v.asInstanceOf[Vector1[_]] + val v1 = v.asInstanceOf[Vector1[?]] depth = 1 setLen(v1.prefix1.length) a1 = copyOrUse(v1.prefix1, 0, WIDTH) case 3 => - val v2 = v.asInstanceOf[Vector2[_]] + val v2 = v.asInstanceOf[Vector2[?]] val d2 = v2.data2 a1 = copyOrUse(v2.suffix1, 0, WIDTH) depth = 2 @@ -1491,7 +1491,7 @@ final class VectorBuilder[A] extends ReusableBuilder[A, Vector[A]] { System.arraycopy(d2, 0, a2, 1, d2.length) a2(d2.length+1) = a1 case 5 => - val v3 = v.asInstanceOf[Vector3[_]] + val v3 = v.asInstanceOf[Vector3[?]] val d3 = v3.data3 val s2 = v3.suffix2 a1 = copyOrUse(v3.suffix1, 0, WIDTH) @@ -1505,7 +1505,7 @@ final class VectorBuilder[A] extends ReusableBuilder[A, Vector[A]] { a3(d3.length+1) = a2 a2(s2.length) = a1 case 7 => - val v4 = v.asInstanceOf[Vector4[_]] + val v4 = v.asInstanceOf[Vector4[?]] val d4 = v4.data4 val s3 = v4.suffix3 val s2 = v4.suffix2 @@ -1522,7 +1522,7 @@ final class VectorBuilder[A] extends ReusableBuilder[A, Vector[A]] { a3(s3.length) = a2 a2(s2.length) = a1 case 9 => - val v5 = v.asInstanceOf[Vector5[_]] + val v5 = v.asInstanceOf[Vector5[?]] val d5 = v5.data5 val s4 = v5.suffix4 val s3 = v5.suffix3 @@ -1542,7 +1542,7 @@ final class VectorBuilder[A] extends ReusableBuilder[A, Vector[A]] { a3(s3.length) = a2 a2(s2.length) = a1 case 11 => - val v6 = v.asInstanceOf[Vector6[_]] + val v6 = v.asInstanceOf[Vector6[?]] val d6 = v6.data6 val s5 = v6.suffix5 val s4 = v6.suffix4 @@ -1608,7 +1608,7 @@ final class VectorBuilder[A] extends ReusableBuilder[A, Vector[A]] { * becomes * a2 = Array(Array(0, 1, .., x), Array(x+1, .., x+32), ..., ?, ..., ?) */ - private[this] def leftAlignPrefix(): Unit = { + private def leftAlignPrefix(): Unit = { @inline def shrinkOffsetIfToLarge(width: Int): Unit = { val newOffset = offset % width lenRest -= offset - newOffset @@ -1708,7 +1708,7 @@ final class VectorBuilder[A] extends ReusableBuilder[A, Vector[A]] { this } - private[this] def addArr1(data: Arr1): Unit = { + private def addArr1(data: Arr1): Unit = { val dl = data.length if(dl > 0) { if(len1 == WIDTH) advance() @@ -1724,7 +1724,7 @@ final class VectorBuilder[A] extends ReusableBuilder[A, Vector[A]] { } } - private[this] def addArrN(slice: Array[AnyRef], dim: Int): Unit = { + private def addArrN(slice: Array[AnyRef], dim: Int): Unit = { // assert(dim >= 2) // assert(lenRest % WIDTH == 0) // assert(len1 == 0 || len1 == WIDTH) @@ -1804,7 +1804,7 @@ final class VectorBuilder[A] extends ReusableBuilder[A, Vector[A]] { } } - private[this] def addVector(xs: Vector[A]): this.type = { + private def addVector(xs: Vector[A]): this.type = { val sliceCount = xs.vectorSliceCount var sliceIdx = 0 while(sliceIdx < sliceCount) { @@ -1828,7 +1828,7 @@ final class VectorBuilder[A] extends ReusableBuilder[A, Vector[A]] { super.addAll(xs) } - private[this] def advance(): Unit = { + private def advance(): Unit = { val idx = lenRest + WIDTH val xor = idx ^ lenRest lenRest = idx @@ -1836,7 +1836,7 @@ final class VectorBuilder[A] extends ReusableBuilder[A, Vector[A]] { advance1(idx, xor) } - private[this] def advanceN(n: Int): Unit = if (n > 0) { + private def advanceN(n: Int): Unit = if (n > 0) { // assert(n % 32 == 0) val idx = lenRest + n val xor = idx ^ lenRest @@ -1845,7 +1845,7 @@ final class VectorBuilder[A] extends ReusableBuilder[A, Vector[A]] { advance1(idx, xor) } - private[this] def advance1(idx: Int, xor: Int): Unit = { + private def advance1(idx: Int, xor: Int): Unit = { if (xor <= 0) { // level = 6 or something very unexpected happened throw new IllegalArgumentException(s"advance1($idx, $xor): a1=$a1, a2=$a2, a3=$a3, a4=$a4, a5=$a5, a6=$a6, depth=$depth") } else if (xor < WIDTH2) { // level = 1 @@ -1984,10 +1984,10 @@ final class VectorBuilder[A] extends ReusableBuilder[A, Vector[A]] { override def toString: String = s"VectorBuilder(len1=$len1, lenRest=$lenRest, offset=$offset, depth=$depth)" - private[immutable] def getData: Array[Array[_]] = Array[Array[AnyRef]]( + private[immutable] def getData: Array[Array[?]] = Array[Array[AnyRef]]( a1, a2.asInstanceOf[Array[AnyRef]], a3.asInstanceOf[Array[AnyRef]], a4.asInstanceOf[Array[AnyRef]], a5.asInstanceOf[Array[AnyRef]], a6.asInstanceOf[Array[AnyRef]] - ).asInstanceOf[Array[Array[_]]] + ).asInstanceOf[Array[Array[?]]] } @@ -2189,7 +2189,7 @@ private object VectorStatics { ac.asInstanceOf[Array[T]] } - final def prepend1IfSpace(prefix1: Arr1, xs: IterableOnce[_]^): Arr1 | Null = xs match { + final def prepend1IfSpace(prefix1: Arr1, xs: IterableOnce[?]^): Arr1 | Null = xs match { case it: Iterable[_] => if(it.sizeCompare(WIDTH-prefix1.length) <= 0) { it.size match { @@ -2214,7 +2214,7 @@ private object VectorStatics { } else null } - final def append1IfSpace(suffix1: Arr1, xs: IterableOnce[_]^): Arr1 | Null = xs match { + final def append1IfSpace(suffix1: Arr1, xs: IterableOnce[?]^): Arr1 | Null = xs match { case it: Iterable[_] => if(it.sizeCompare(WIDTH-suffix1.length) <= 0) { it.size match { @@ -2239,23 +2239,23 @@ private object VectorStatics { } -private final class NewVectorIterator[A](v: Vector[A], private[this] var totalLength: Int, private[this] val sliceCount: Int) extends AbstractIterator[A] with java.lang.Cloneable { +private final class NewVectorIterator[A](v: Vector[A], private var totalLength: Int, private val sliceCount: Int) extends AbstractIterator[A] with java.lang.Cloneable { - private[this] var a1: Arr1 = v.prefix1 - private[this] var a2: Arr2 = _ - private[this] var a3: Arr3 = _ - private[this] var a4: Arr4 = _ - private[this] var a5: Arr5 = _ - private[this] var a6: Arr6 = _ - private[this] var a1len = a1.length - private[this] var i1 = 0 // current index in a1 - private[this] var oldPos = 0 - private[this] var len1 = totalLength // remaining length relative to a1 + private var a1: Arr1 = v.prefix1 + private var a2: Arr2 = compiletime.uninitialized + private var a3: Arr3 = compiletime.uninitialized + private var a4: Arr4 = compiletime.uninitialized + private var a5: Arr5 = compiletime.uninitialized + private var a6: Arr6 = compiletime.uninitialized + private var a1len = a1.length + private var i1 = 0 // current index in a1 + private var oldPos = 0 + private var len1 = totalLength // remaining length relative to a1 - private[this] var sliceIdx = 0 - private[this] var sliceDim = 1 - private[this] var sliceStart = 0 // absolute position - private[this] var sliceEnd = a1len // absolute position + private var sliceIdx = 0 + private var sliceDim = 1 + private var sliceStart = 0 // absolute position + private var sliceEnd = a1len // absolute position //override def toString: String = // s"NewVectorIterator(v=$v, totalLength=$totalLength, sliceCount=$sliceCount): a1len=$a1len, len1=$len1, i1=$i1, sliceEnd=$sliceEnd" @@ -2271,10 +2271,10 @@ private final class NewVectorIterator[A](v: Vector[A], private[this] var totalLe r.asInstanceOf[A] } - private[this] def advanceSlice(): Unit = { + private def advanceSlice(): Unit = { if(!hasNext) Iterator.empty.next() sliceIdx += 1 - var slice: Array[_ <: AnyRef | Null] = v.vectorSlice(sliceIdx) + var slice: Array[? <: AnyRef | Null] = v.vectorSlice(sliceIdx) while(slice.length == 0) { sliceIdx += 1 slice = v.vectorSlice(sliceIdx) @@ -2294,7 +2294,7 @@ private final class NewVectorIterator[A](v: Vector[A], private[this] var totalLe if(sliceDim > 1) oldPos = (1 << (BITS*sliceDim))-1 } - private[this] def advance(): Unit = { + private def advance(): Unit = { val pos = i1-len1+totalLength if(pos == sliceEnd) advanceSlice() if(sliceDim > 1) { @@ -2308,7 +2308,7 @@ private final class NewVectorIterator[A](v: Vector[A], private[this] var totalLe i1 = 0 } - private[this] def advanceA(io: Int, xor: Int): Unit = { + private def advanceA(io: Int, xor: Int): Unit = { if(xor < WIDTH2) { a1 = a2((io >>> BITS) & MASK) } else if(xor < WIDTH3) { @@ -2332,7 +2332,7 @@ private final class NewVectorIterator[A](v: Vector[A], private[this] var totalLe } } - private[this] def setA(io: Int, xor: Int): Unit = { + private def setA(io: Int, xor: Int): Unit = { if(xor < WIDTH2) { a1 = a2((io >>> BITS) & MASK) } else if(xor < WIDTH3) { @@ -2434,7 +2434,7 @@ private final class NewVectorIterator[A](v: Vector[A], private[this] var totalLe private abstract class VectorStepperBase[A, Sub <: Stepper[A], Semi <: Sub](it: NewVectorIterator[A]) extends Stepper[A] with EfficientSplit { - protected[this] def build(it: NewVectorIterator[A]): Semi + protected def build(it: NewVectorIterator[A]): Semi final def hasStep: Boolean = it.hasNext @@ -2453,32 +2453,32 @@ private abstract class VectorStepperBase[A, Sub <: Stepper[A], Semi <: Sub](it: private class AnyVectorStepper[A](it: NewVectorIterator[A]) extends VectorStepperBase[A, AnyStepper[A], AnyVectorStepper[A]](it) with AnyStepper[A] { - protected[this] def build(it: NewVectorIterator[A]) = new AnyVectorStepper(it) + protected def build(it: NewVectorIterator[A]) = new AnyVectorStepper(it) def nextStep(): A = it.next() } private class DoubleVectorStepper(it: NewVectorIterator[Double]) extends VectorStepperBase[Double, DoubleStepper, DoubleVectorStepper](it) with DoubleStepper { - protected[this] def build(it: NewVectorIterator[Double]) = new DoubleVectorStepper(it) + protected def build(it: NewVectorIterator[Double]) = new DoubleVectorStepper(it) def nextStep(): Double = it.next() } private class IntVectorStepper(it: NewVectorIterator[Int]) extends VectorStepperBase[Int, IntStepper, IntVectorStepper](it) with IntStepper { - protected[this] def build(it: NewVectorIterator[Int]) = new IntVectorStepper(it) + protected def build(it: NewVectorIterator[Int]) = new IntVectorStepper(it) def nextStep(): Int = it.next() } private class LongVectorStepper(it: NewVectorIterator[Long]) extends VectorStepperBase[Long, LongStepper, LongVectorStepper](it) with LongStepper { - protected[this] def build(it: NewVectorIterator[Long]) = new LongVectorStepper(it) + protected def build(it: NewVectorIterator[Long]) = new LongVectorStepper(it) def nextStep(): Long = it.next() } // The following definitions are needed for binary compatibility with ParVector -private[collection] class VectorIterator[+A](_startIndex: Int, private[this] var endIndex: Int) extends AbstractIterator[A] { - private[immutable] var it: NewVectorIterator[A @uncheckedVariance] = _ +private[collection] class VectorIterator[+A](_startIndex: Int, private var endIndex: Int) extends AbstractIterator[A] { + private[immutable] var it: NewVectorIterator[A @uncheckedVariance] = compiletime.uninitialized def hasNext: Boolean = it.hasNext def next(): A = it.next() private[collection] def remainingElementCount: Int = it.size diff --git a/library/src/scala/collection/immutable/VectorMap.scala b/library/src/scala/collection/immutable/VectorMap.scala index ffd87448e97d..59c86c4b457c 100644 --- a/library/src/scala/collection/immutable/VectorMap.scala +++ b/library/src/scala/collection/immutable/VectorMap.scala @@ -41,7 +41,7 @@ final class VectorMap[K, +V] private ( import VectorMap._ - override protected[this] def className: String = "VectorMap" + override protected def className: String = "VectorMap" private[immutable] def this(fields: Vector[K], underlying: Map[K, (Int, V)]) = this(fields, underlying, 0) @@ -81,11 +81,11 @@ final class VectorMap[K, +V] private ( } def iterator: Iterator[(K, V)] = new AbstractIterator[(K, V)] { - private[this] val fieldsLength = fields.length - private[this] var slot = -1 - private[this] var key: K = null.asInstanceOf[K] + private val fieldsLength = fields.length + private var slot = -1 + private var key: K = null.asInstanceOf[K] - private[this] def advance(): Unit = { + private def advance(): Unit = { val nextSlot = slot + 1 if (nextSlot >= fieldsLength) { slot = fieldsLength @@ -118,11 +118,11 @@ final class VectorMap[K, +V] private ( // No-Op overrides to allow for more efficient steppers in a minor release. // Refining the return type to `S with EfficientSplit` is binary compatible. - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[(K, V), S]): S = super.stepper(shape) + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[(K, V), S]): S = super.stepper(using shape) - override def keyStepper[S <: Stepper[_]](implicit shape: StepperShape[K, S]): S = super.keyStepper(shape) + override def keyStepper[S <: Stepper[?]](implicit shape: StepperShape[K, S]): S = super.keyStepper(using shape) - override def valueStepper[S <: Stepper[_]](implicit shape: StepperShape[V, S]): S = super.valueStepper(shape) + override def valueStepper[S <: Stepper[?]](implicit shape: StepperShape[V, S]): S = super.valueStepper(using shape) def removed(key: K): VectorMap[K, V] = { @@ -230,7 +230,7 @@ object VectorMap extends MapFactory[VectorMap] { //For other deleted slots, it simply indicates that they have been deleted. private[VectorMap] final case class Tombstone(distance: Int) - private[this] final val EmptyMap: VectorMap[Nothing, Nothing] = + private final val EmptyMap: VectorMap[Nothing, Nothing] = new VectorMap[Nothing, Nothing](Vector.empty[Nothing], HashMap.empty[Nothing, (Int, Nothing)]) def empty[K, V]: VectorMap[K, V] = EmptyMap.asInstanceOf[VectorMap[K, V]] @@ -245,10 +245,10 @@ object VectorMap extends MapFactory[VectorMap] { } private[immutable] final class VectorMapBuilder[K, V] extends mutable.Builder[(K, V), VectorMap[K, V]] { - private[this] val vectorBuilder = new VectorBuilder[K] - private[this] val mapBuilder = new MapBuilderImpl[K, (Int, V)] + private val vectorBuilder = new VectorBuilder[K] + private val mapBuilder = new MapBuilderImpl[K, (Int, V)] @annotation.stableNull - private[this] var aliased: VectorMap[K, V] | Null = null + private var aliased: VectorMap[K, V] | Null = null override def clear(): Unit = { vectorBuilder.clear() diff --git a/library/src/scala/collection/immutable/WrappedString.scala b/library/src/scala/collection/immutable/WrappedString.scala index 4ff83b8c47dd..38b2b0fc1e0d 100644 --- a/library/src/scala/collection/immutable/WrappedString.scala +++ b/library/src/scala/collection/immutable/WrappedString.scala @@ -57,7 +57,7 @@ final class WrappedString(private val self: String) extends AbstractSeq[Char] wi override def toString = self override def view: StringView = new StringView(self) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[Char, S]): S with EfficientSplit = { + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[Char, S]): S & EfficientSplit = { val st = new CharStringStepper(self, 0, self.length) val r = if (shape.shape == StepperShape.CharShape) st @@ -65,7 +65,7 @@ final class WrappedString(private val self: String) extends AbstractSeq[Char] wi assert(shape.shape == StepperShape.ReferenceShape, s"unexpected StepperShape: $shape") AnyStepper.ofParIntStepper(st) } - r.asInstanceOf[S with EfficientSplit] + r.asInstanceOf[S & EfficientSplit] } override def startsWith[B >: Char](that: IterableOnce[B]^, offset: Int = 0): Boolean = @@ -102,7 +102,7 @@ final class WrappedString(private val self: String) extends AbstractSeq[Char] wi override def appendedAll[B >: Char](suffix: IterableOnce[B]^): IndexedSeq[B] = suffix match { - case s: WrappedString => new WrappedString(self concat s.self) + case s: WrappedString => new WrappedString(self.concat(s.self)) case _ => super.appendedAll(suffix) } @@ -111,7 +111,7 @@ final class WrappedString(private val self: String) extends AbstractSeq[Char] wi case _ => super.sameElements(o) } - override protected[this] def className = "WrappedString" + override protected def className = "WrappedString" override protected final def applyPreferredMaxLength: Int = Int.MaxValue override def equals(other: Any): Boolean = other match { diff --git a/library/src/scala/collection/mutable/AnyRefMap.scala b/library/src/scala/collection/mutable/AnyRefMap.scala index 8228254ddfe2..aede46230311 100644 --- a/library/src/scala/collection/mutable/AnyRefMap.scala +++ b/library/src/scala/collection/mutable/AnyRefMap.scala @@ -67,16 +67,16 @@ class AnyRefMap[K <: AnyRef, V] private[collection] (defaultEntry: K -> V, initi /** Creates a new `AnyRefMap` with specified default values and initial buffer size. */ def this(defaultEntry: K -> V, initialBufferSize: Int) = this(defaultEntry, initialBufferSize, initBlank = true) - private[this] var mask = 0 - private[this] var _size = 0 - private[this] var _vacant = 0 - private[this] var _hashes: Array[Int] = _ - private[this] var _keys: Array[AnyRef | Null] = _ - private[this] var _values: Array[AnyRef | Null] = _ + private var mask = 0 + private var _size = 0 + private var _vacant = 0 + private var _hashes: Array[Int] = compiletime.uninitialized + private var _keys: Array[AnyRef | Null] = compiletime.uninitialized + private var _values: Array[AnyRef | Null] = compiletime.uninitialized if (initBlank) defaultInitialize(initialBufferSize) - private[this] def defaultInitialize(n: Int): Unit = { + private def defaultInitialize(n: Int): Unit = { mask = if (n<0) 0x7 else (((1 << (32 - java.lang.Integer.numberOfLeadingZeros(n-1))) - 1) & 0x3FFFFFFF) | 0x7 @@ -128,7 +128,7 @@ class AnyRefMap[K <: AnyRef, V] private[collection] (defaultEntry: K -> V, initi val hashes = _hashes val keys = _keys while ({ g = hashes(e); g != 0}) { - if (g == h && { val q = keys(e); (q eq k) || ((q ne null) && (q equals k)) }) return e + if (g == h && { val q = keys(e); (q eq k) || ((q ne null) && (q.equals(k))) }) return e x += 1 e = (e + 2*(x+1)*x - 3) & mask } @@ -141,7 +141,7 @@ class AnyRefMap[K <: AnyRef, V] private[collection] (defaultEntry: K -> V, initi var g = 0 var o = -1 while ({ g = _hashes(e); g != 0}) { - if (g == h && { val q = _keys(e); (q eq k) || ((q ne null) && (q equals k)) }) return e + if (g == h && { val q = _keys(e); (q eq k) || ((q ne null) && (q.equals(k))) }) return e else if (o == -1 && g+g == 0) o = e x += 1 e = (e + 2*(x+1)*x - 3) & mask @@ -334,11 +334,11 @@ class AnyRefMap[K <: AnyRef, V] private[collection] (defaultEntry: K -> V, initi } private abstract class AnyRefMapIterator[A] extends AbstractIterator[A] { - private[this] val hz = _hashes - private[this] val kz = _keys - private[this] val vz = _values + private val hz = _hashes + private val kz = _keys + private val vz = _values - private[this] var index = 0 + private var index = 0 def hasNext: Boolean = index < hz.length && { var h = hz(index) @@ -422,7 +422,7 @@ class AnyRefMap[K <: AnyRef, V] private[collection] (defaultEntry: K -> V, initi override def updated[V1 >: V](key: K, value: V1): AnyRefMap[K, V1] = clone().asInstanceOf[AnyRefMap[K, V1]].addOne(key, value) - private[this] def foreachElement[A,B](elems: Array[AnyRef | Null], f: A => B): Unit = { + private def foreachElement[A,B](elems: Array[AnyRef | Null], f: A => B): Unit = { var i,j = 0 while (i < _hashes.length & j < _size) { val h = _hashes(i) @@ -520,10 +520,10 @@ class AnyRefMap[K <: AnyRef, V] private[collection] (defaultEntry: K -> V, initi _vacant = 0 } - protected[this] def writeReplace(): AnyRef = new DefaultSerializationProxy(AnyRefMap.toFactory[K, V](AnyRefMap), this) + protected def writeReplace(): AnyRef = new DefaultSerializationProxy(AnyRefMap.toFactory[K, V](AnyRefMap), this) @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix = "AnyRefMap" + override protected def stringPrefix = "AnyRefMap" } @deprecated("Use `scala.collection.mutable.HashMap` instead for better performance.", since = "2.13.16") @@ -614,18 +614,18 @@ object AnyRefMap { implicit def toFactory[K <: AnyRef, V](dummy: AnyRefMap.type): Factory[(K, V), AnyRefMap[K, V]] = ToFactory.asInstanceOf[Factory[(K, V), AnyRefMap[K, V]]] @SerialVersionUID(3L) - private[this] object ToFactory extends Factory[(AnyRef, AnyRef), AnyRefMap[AnyRef, AnyRef]] with Serializable { + private object ToFactory extends Factory[(AnyRef, AnyRef), AnyRefMap[AnyRef, AnyRef]] with Serializable { def fromSpecific(it: IterableOnce[(AnyRef, AnyRef)]^): AnyRefMap[AnyRef, AnyRef] = AnyRefMap.from[AnyRef, AnyRef](it) def newBuilder: Builder[(AnyRef, AnyRef), AnyRefMap[AnyRef, AnyRef]] = AnyRefMap.newBuilder[AnyRef, AnyRef] } implicit def toBuildFrom[K <: AnyRef, V](factory: AnyRefMap.type): BuildFrom[Any, (K, V), AnyRefMap[K, V]] = ToBuildFrom.asInstanceOf[BuildFrom[Any, (K, V), AnyRefMap[K, V]]] - private[this] object ToBuildFrom extends BuildFrom[Any, (AnyRef, AnyRef), AnyRefMap[AnyRef, AnyRef]] { + private object ToBuildFrom extends BuildFrom[Any, (AnyRef, AnyRef), AnyRefMap[AnyRef, AnyRef]] { def fromSpecific(from: Any)(it: IterableOnce[(AnyRef, AnyRef)]^): AnyRefMap[AnyRef, AnyRef] = AnyRefMap.from(it) def newBuilder(from: Any): ReusableBuilder[(AnyRef, AnyRef), AnyRefMap[AnyRef, AnyRef]] = AnyRefMap.newBuilder[AnyRef, AnyRef] } implicit def iterableFactory[K <: AnyRef, V]: Factory[(K, V), AnyRefMap[K, V]] = toFactory[K, V](this) - implicit def buildFromAnyRefMap[K <: AnyRef, V]: BuildFrom[AnyRefMap[_, _], (K, V), AnyRefMap[K, V]] = toBuildFrom(this) + implicit def buildFromAnyRefMap[K <: AnyRef, V]: BuildFrom[AnyRefMap[?, ?], (K, V), AnyRefMap[K, V]] = toBuildFrom(this) } diff --git a/library/src/scala/collection/mutable/ArrayBuffer.scala b/library/src/scala/collection/mutable/ArrayBuffer.scala index b8fa9c806e5e..241287794e71 100644 --- a/library/src/scala/collection/mutable/ArrayBuffer.scala +++ b/library/src/scala/collection/mutable/ArrayBuffer.scala @@ -52,15 +52,15 @@ class ArrayBuffer[A] private (initialElements: Array[AnyRef], initialSize: Int) def this(initialSize: Int) = this(new Array[AnyRef](initialSize max 1), 0) - @transient private[this] var mutationCount: Int = 0 + @transient private var mutationCount: Int = 0 // needs to be `private[collection]` or `protected[collection]` for parallel-collections protected[collection] var array: Array[AnyRef] = initialElements protected var size0 = initialSize - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[A, S]): S with EfficientSplit = { + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[A, S]): S & EfficientSplit = { import scala.collection.convert.impl._ - shape.parUnbox(new ObjectArrayStepper(array, 0, length).asInstanceOf[AnyStepper[A] with EfficientSplit]) + shape.parUnbox(new ObjectArrayStepper(array, 0, length).asInstanceOf[AnyStepper[A] & EfficientSplit]) } override def knownSize: Int = super[IndexedSeqOps].knownSize @@ -234,7 +234,7 @@ class ArrayBuffer[A] private (initialElements: Array[AnyRef], initialSize: Int) @inline def mapResult[NewTo](f: (ArrayBuffer[A]) => NewTo): Builder[A, NewTo]^{f} = new GrowableBuilder[A, ArrayBuffer[A]](this).mapResult(f) @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix = "ArrayBuffer" + override protected def stringPrefix = "ArrayBuffer" override def copyToArray[B >: A](xs: Array[B], start: Int, len: Int): Int = { val copied = IterableOnce.elemsToCopyToArray(length, xs.length, start, len) @@ -293,7 +293,7 @@ class ArrayBuffer[A] private (initialElements: Array[AnyRef], initialSize: Int) @SerialVersionUID(3L) object ArrayBuffer extends StrictOptimizedSeqFactory[ArrayBuffer] { final val DefaultInitialSize = 16 - private[this] val emptyArray = new Array[AnyRef](0) + private val emptyArray = new Array[AnyRef](0) def from[B](coll: collection.IterableOnce[B]^): ArrayBuffer[B] = { val k = coll.knownSize @@ -387,7 +387,7 @@ final class ArrayBufferView[A] private[mutable](underlying: ArrayBuffer[A], muta @throws[IndexOutOfBoundsException] def apply(n: Int): A = underlying(n) def length: Int = underlying.length - override protected[this] def className = "ArrayBufferView" + override protected def className = "ArrayBufferView" // we could inherit all these from `CheckedIndexedSeqView`, except this class is public override def iterator: Iterator[A]^{this} = new CheckedIndexedSeqView.CheckedIterator(this, mutationCount()) diff --git a/library/src/scala/collection/mutable/ArrayBuilder.scala b/library/src/scala/collection/mutable/ArrayBuilder.scala index c1af54f73af0..1b27496e554a 100644 --- a/library/src/scala/collection/mutable/ArrayBuilder.scala +++ b/library/src/scala/collection/mutable/ArrayBuilder.scala @@ -26,8 +26,8 @@ import scala.reflect.ClassTag sealed abstract class ArrayBuilder[T] extends ReusableBuilder[T, Array[T]] with Serializable { - protected[this] var capacity: Int = 0 - protected[this] def elems: Array[T] | Null // may not be allocated at size = capacity = 0 + protected var capacity: Int = 0 + protected def elems: Array[T] | Null // may not be allocated at size = capacity = 0 protected var size: Int = 0 /** Current number of elements. */ @@ -36,7 +36,7 @@ sealed abstract class ArrayBuilder[T] /** Current number of elements. */ override def knownSize: Int = size - protected[this] final def ensureSize(size: Int): Unit = { + protected final def ensureSize(size: Int): Unit = { val newLen = resizeUp(capacity, size) if (newLen > 0) resize(newLen) } @@ -45,20 +45,20 @@ sealed abstract class ArrayBuilder[T] def clear(): Unit = size = 0 - protected[this] def resize(size: Int): Unit + protected def resize(size: Int): Unit /** Add all elements of an array. */ - def addAll(xs: Array[_ <: T]): this.type = addAll(xs, 0, xs.length) + def addAll(xs: Array[? <: T]): this.type = addAll(xs, 0, xs.length) /** Add a slice of an array. */ - def addAll(xs: Array[_ <: T], offset: Int, length: Int): this.type = { + def addAll(xs: Array[? <: T], offset: Int, length: Int): this.type = { val offset1 = offset.max(0) val length1 = length.max(0) val effectiveLength = length1.min(xs.length - offset1) doAddAll(xs, offset1, effectiveLength) } - private def doAddAll(xs: Array[_ <: T], offset: Int, length: Int): this.type = { + private def doAddAll(xs: Array[? <: T], offset: Int, length: Int): this.type = { if (length > 0) { ensureSize(this.size + length) Array.copy(xs, offset, elems.nn, this.size, length) @@ -100,7 +100,7 @@ object ArrayBuilder { case java.lang.Double.TYPE => new ArrayBuilder.ofDouble().asInstanceOf[ArrayBuilder[T]] case java.lang.Boolean.TYPE => new ArrayBuilder.ofBoolean().asInstanceOf[ArrayBuilder[T]] case java.lang.Void.TYPE => new ArrayBuilder.ofUnit().asInstanceOf[ArrayBuilder[T]] - case _ => new ArrayBuilder.ofRef[T with AnyRef]()(tag.asInstanceOf[ClassTag[T with AnyRef]]).asInstanceOf[ArrayBuilder[T]] + case _ => new ArrayBuilder.ofRef[T & AnyRef]()(using tag.asInstanceOf[ClassTag[T & AnyRef]]).asInstanceOf[ArrayBuilder[T]] } } @@ -121,7 +121,7 @@ object ArrayBuilder { else java.util.Arrays.copyOf[T](elems, size) } - protected[this] def resize(size: Int): Unit = { + protected def resize(size: Int): Unit = { elems = mkArray(size) capacity = size } @@ -168,7 +168,7 @@ object ArrayBuilder { newelems } - protected[this] def resize(size: Int): Unit = { + protected def resize(size: Int): Unit = { elems = mkArray(size) capacity = size } @@ -210,7 +210,7 @@ object ArrayBuilder { newelems } - protected[this] def resize(size: Int): Unit = { + protected def resize(size: Int): Unit = { elems = mkArray(size) capacity = size } @@ -252,7 +252,7 @@ object ArrayBuilder { newelems } - protected[this] def resize(size: Int): Unit = { + protected def resize(size: Int): Unit = { elems = mkArray(size) capacity = size } @@ -294,7 +294,7 @@ object ArrayBuilder { newelems } - protected[this] def resize(size: Int): Unit = { + protected def resize(size: Int): Unit = { elems = mkArray(size) capacity = size } @@ -336,7 +336,7 @@ object ArrayBuilder { newelems } - protected[this] def resize(size: Int): Unit = { + protected def resize(size: Int): Unit = { elems = mkArray(size) capacity = size } @@ -378,7 +378,7 @@ object ArrayBuilder { newelems } - protected[this] def resize(size: Int): Unit = { + protected def resize(size: Int): Unit = { elems = mkArray(size) capacity = size } @@ -420,7 +420,7 @@ object ArrayBuilder { newelems } - protected[this] def resize(size: Int): Unit = { + protected def resize(size: Int): Unit = { elems = mkArray(size) capacity = size } @@ -463,7 +463,7 @@ object ArrayBuilder { newelems } - protected[this] def resize(size: Int): Unit = { + protected def resize(size: Int): Unit = { elems = mkArray(size) capacity = size } @@ -513,7 +513,7 @@ object ArrayBuilder { this } - override def addAll(xs: Array[_ <: Unit], offset: Int, length: Int): this.type = { + override def addAll(xs: Array[? <: Unit], offset: Int, length: Int): this.type = { val newSize = size + length ensureSize(newSize) size = newSize @@ -532,7 +532,7 @@ object ArrayBuilder { case _ => false } - protected[this] def resize(size: Int): Unit = capacity = size + protected def resize(size: Int): Unit = capacity = size override def toString = "ArrayBuilder.ofUnit" } diff --git a/library/src/scala/collection/mutable/ArrayDeque.scala b/library/src/scala/collection/mutable/ArrayDeque.scala index 08a89754720a..4974e43ef532 100644 --- a/library/src/scala/collection/mutable/ArrayDeque.scala +++ b/library/src/scala/collection/mutable/ArrayDeque.scala @@ -53,7 +53,7 @@ class ArrayDeque[A] protected ( reset(array, start, end) - private[this] def reset(array: Array[AnyRef | Null], start: Int, end: Int) = { + private def reset(array: Array[AnyRef | Null], start: Int, end: Int) = { assert((array.length & (array.length - 1)) == 0, s"Array.length must be power of 2") requireBounds(idx = start, until = array.length) requireBounds(idx = end, until = array.length) @@ -67,7 +67,7 @@ class ArrayDeque[A] protected ( override def knownSize: Int = super[IndexedSeqOps].knownSize // No-Op override to allow for more efficient stepper in a minor release. - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[A, S]): S with EfficientSplit = super.stepper(shape) + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[A, S]): S & EfficientSplit = super.stepper(using shape) def apply(idx: Int): A = { requireBounds(idx) @@ -306,7 +306,7 @@ class ArrayDeque[A] protected ( def removeHead(resizeInternalRepr: Boolean = false): A = if (isEmpty) throw new NoSuchElementException(s"empty collection") else removeHeadAssumingNonEmpty(resizeInternalRepr) - @inline private[this] def removeHeadAssumingNonEmpty(resizeInternalRepr: Boolean = false): A = { + @inline private def removeHeadAssumingNonEmpty(resizeInternalRepr: Boolean = false): A = { val elem = array(start) array(start) = null start = start_+(1) @@ -333,7 +333,7 @@ class ArrayDeque[A] protected ( def removeLast(resizeInternalRepr: Boolean = false): A = if (isEmpty) throw new NoSuchElementException(s"empty collection") else removeLastAssumingNonEmpty(resizeInternalRepr) - @`inline` private[this] def removeLastAssumingNonEmpty(resizeInternalRepr: Boolean = false): A = { + @`inline` private def removeLastAssumingNonEmpty(resizeInternalRepr: Boolean = false): A = { end = end_-(1) val elem = array(end) array(end) = null @@ -484,41 +484,41 @@ class ArrayDeque[A] protected ( // Utils for common modular arithmetic: @inline protected def start_+(idx: Int) = (start + idx) & (array.length - 1) - @inline private[this] def start_-(idx: Int) = (start - idx) & (array.length - 1) - @inline private[this] def end_+(idx: Int) = (end + idx) & (array.length - 1) - @inline private[this] def end_-(idx: Int) = (end - idx) & (array.length - 1) + @inline private def start_-(idx: Int) = (start - idx) & (array.length - 1) + @inline private def end_+(idx: Int) = (end + idx) & (array.length - 1) + @inline private def end_-(idx: Int) = (end - idx) & (array.length - 1) // Note: here be overflow dragons! This is used for int overflow // assumptions in resize(). Use caution changing. - @inline private[this] def mustGrow(len: Int) = { + @inline private def mustGrow(len: Int) = { len >= array.length } // Assumes that 0 <= len < array.length! - @inline private[this] def shouldShrink(len: Int) = { + @inline private def shouldShrink(len: Int) = { // To avoid allocation churn, only shrink when array is large // and less than 2/5 filled. array.length > ArrayDeque.StableSize && array.length - len - (len >> 1) > len } // Assumes that 0 <= len < array.length! - @inline private[this] def canShrink(len: Int) = { + @inline private def canShrink(len: Int) = { array.length > ArrayDeque.DefaultInitialSize && array.length - len > len } - @inline private[this] def _get(idx: Int): A = array(start_+(idx)).asInstanceOf[A] + @inline private def _get(idx: Int): A = array(start_+(idx)).asInstanceOf[A] - @inline private[this] def _set(idx: Int, elem: A) = array(start_+(idx)) = elem.asInstanceOf[AnyRef] + @inline private def _set(idx: Int, elem: A) = array(start_+(idx)) = elem.asInstanceOf[AnyRef] // Assumes that 0 <= len. - private[this] def resize(len: Int) = if (mustGrow(len) || canShrink(len)) { + private def resize(len: Int) = if (mustGrow(len) || canShrink(len)) { val n = length val array2 = copySliceToArray(srcStart = 0, dest = ArrayDeque.alloc(len), destStart = 0, maxItems = n) reset(array = array2, start = 0, end = n) } @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix = "ArrayDeque" + override protected def stringPrefix = "ArrayDeque" } /** @@ -595,7 +595,7 @@ transparent trait ArrayDequeOps[A, +CC[_] <: caps.Pure, +C <: AnyRef] extends St * @param destStart * @param maxItems */ - def copySliceToArray(srcStart: Int, dest: Array[_], destStart: Int, maxItems: Int): dest.type = { + def copySliceToArray(srcStart: Int, dest: Array[?], destStart: Int, maxItems: Int): dest.type = { requireBounds(destStart, dest.length+1) val toCopy = Math.min(maxItems, Math.min(length - srcStart, dest.length - destStart)) if (toCopy > 0) { diff --git a/library/src/scala/collection/mutable/ArraySeq.scala b/library/src/scala/collection/mutable/ArraySeq.scala index 695c9567b597..fe2c9d18ecad 100644 --- a/library/src/scala/collection/mutable/ArraySeq.scala +++ b/library/src/scala/collection/mutable/ArraySeq.scala @@ -56,7 +56,7 @@ sealed abstract class ArraySeq[T] /** The tag of the element type. This does not have to be equal to the element type of this ArraySeq. A primitive * ArraySeq can be backed by an array of boxed values and a reference ArraySeq can be backed by an array of a supertype * or subtype of the element type. */ - def elemTag: ClassTag[_] + def elemTag: ClassTag[?] /** Update element at given index */ def update(@deprecatedName("idx", "2.13.0") index: Int, elem: T): Unit @@ -64,11 +64,11 @@ sealed abstract class ArraySeq[T] /** The underlying array. Its element type does not have to be equal to the element type of this ArraySeq. A primitive * ArraySeq can be backed by an array of boxed values and a reference ArraySeq can be backed by an array of a supertype * or subtype of the element type. */ - def array: Array[_] + def array: Array[?] - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[T, S]): S with EfficientSplit + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[T, S]): S & EfficientSplit - override protected[this] def className = "ArraySeq" + override protected def className = "ArraySeq" /** Clones this object, including the underlying Array. */ override def clone(): ArraySeq[T] = ArraySeq.make(array.clone()).asInstanceOf[ArraySeq[T]] @@ -89,7 +89,7 @@ sealed abstract class ArraySeq[T] } override def sorted[B >: T](implicit ord: Ordering[B]): ArraySeq[T] = - ArraySeq.make(array.sorted(ord.asInstanceOf[Ordering[Any]])).asInstanceOf[ArraySeq[T]] + ArraySeq.make(array.sorted(using ord.asInstanceOf[Ordering[Any]])).asInstanceOf[ArraySeq[T]] override def sortInPlace[B >: T]()(implicit ord: Ordering[B]): this.type = { if (length > 1) scala.util.Sorting.stableSort(array.asInstanceOf[Array[B]]) @@ -104,7 +104,7 @@ object ArraySeq extends StrictOptimizedClassTagSeqFactory[ArraySeq] { self => val untagged: SeqFactory[ArraySeq] = new ClassTagSeqFactory.AnySeqDelegate(self) // This is reused for all calls to empty. - private[this] val EmptyArraySeq = new ofRef[AnyRef](new Array[AnyRef](0)) + private val EmptyArraySeq = new ofRef[AnyRef](new Array[AnyRef](0)) def empty[T : ClassTag]: ArraySeq[T] = EmptyArraySeq.asInstanceOf[ArraySeq[T]] def from[A : ClassTag](it: scala.collection.IterableOnce[A]^): ArraySeq[A] = make(Array.from[A](it)) @@ -152,11 +152,11 @@ object ArraySeq extends StrictOptimizedClassTagSeqFactory[ArraySeq] { self => case _ => super.equals(that) } override def iterator: Iterator[T] = new ArrayOps.ArrayIterator[T](array) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[T, S]): S with EfficientSplit = ( + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[T, S]): S & EfficientSplit = ( if(shape.shape == StepperShape.ReferenceShape) new ObjectArrayStepper(array, 0, array.length) - else shape.parUnbox(new ObjectArrayStepper(array, 0, array.length).asInstanceOf[AnyStepper[T] with EfficientSplit]) - ).asInstanceOf[S with EfficientSplit] + else shape.parUnbox(new ObjectArrayStepper(array, 0, array.length).asInstanceOf[AnyStepper[T] & EfficientSplit]) + ).asInstanceOf[S & EfficientSplit] } @SerialVersionUID(3L) @@ -172,11 +172,11 @@ object ArraySeq extends StrictOptimizedClassTagSeqFactory[ArraySeq] { self => case _ => super.equals(that) } override def iterator: Iterator[Byte] = new ArrayOps.ArrayIterator[Byte](array) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[Byte, S]): S with EfficientSplit = ( + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[Byte, S]): S & EfficientSplit = ( if(shape.shape == StepperShape.ReferenceShape) AnyStepper.ofParIntStepper(new WidenedByteArrayStepper(array, 0, array.length)) else new WidenedByteArrayStepper(array, 0, array.length) - ).asInstanceOf[S with EfficientSplit] + ).asInstanceOf[S & EfficientSplit] } @SerialVersionUID(3L) @@ -192,11 +192,11 @@ object ArraySeq extends StrictOptimizedClassTagSeqFactory[ArraySeq] { self => case _ => super.equals(that) } override def iterator: Iterator[Short] = new ArrayOps.ArrayIterator[Short](array) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[Short, S]): S with EfficientSplit = ( + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[Short, S]): S & EfficientSplit = ( if(shape.shape == StepperShape.ReferenceShape) AnyStepper.ofParIntStepper(new WidenedShortArrayStepper(array, 0, array.length)) else new WidenedShortArrayStepper(array, 0, array.length) - ).asInstanceOf[S with EfficientSplit] + ).asInstanceOf[S & EfficientSplit] } @SerialVersionUID(3L) @@ -212,11 +212,11 @@ object ArraySeq extends StrictOptimizedClassTagSeqFactory[ArraySeq] { self => case _ => super.equals(that) } override def iterator: Iterator[Char] = new ArrayOps.ArrayIterator[Char](array) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[Char, S]): S with EfficientSplit = ( + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[Char, S]): S & EfficientSplit = ( if(shape.shape == StepperShape.ReferenceShape) AnyStepper.ofParIntStepper(new WidenedCharArrayStepper(array, 0, array.length)) else new WidenedCharArrayStepper(array, 0, array.length) - ).asInstanceOf[S with EfficientSplit] + ).asInstanceOf[S & EfficientSplit] override def addString(sb: StringBuilder, start: String, sep: String, end: String): sb.type = { val jsb = sb.underlying @@ -253,11 +253,11 @@ object ArraySeq extends StrictOptimizedClassTagSeqFactory[ArraySeq] { self => case _ => super.equals(that) } override def iterator: Iterator[Int] = new ArrayOps.ArrayIterator[Int](array) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[Int, S]): S with EfficientSplit = ( + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[Int, S]): S & EfficientSplit = ( if(shape.shape == StepperShape.ReferenceShape) AnyStepper.ofParIntStepper(new IntArrayStepper(array, 0, array.length)) else new IntArrayStepper(array, 0, array.length) - ).asInstanceOf[S with EfficientSplit] + ).asInstanceOf[S & EfficientSplit] } @SerialVersionUID(3L) @@ -273,11 +273,11 @@ object ArraySeq extends StrictOptimizedClassTagSeqFactory[ArraySeq] { self => case _ => super.equals(that) } override def iterator: Iterator[Long] = new ArrayOps.ArrayIterator[Long](array) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[Long, S]): S with EfficientSplit = ( + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[Long, S]): S & EfficientSplit = ( if(shape.shape == StepperShape.ReferenceShape) AnyStepper.ofParLongStepper(new LongArrayStepper(array, 0, array.length)) else new LongArrayStepper(array, 0, array.length) - ).asInstanceOf[S with EfficientSplit] + ).asInstanceOf[S & EfficientSplit] } @SerialVersionUID(3L) @@ -299,11 +299,11 @@ object ArraySeq extends StrictOptimizedClassTagSeqFactory[ArraySeq] { self => case _ => super.equals(that) } override def iterator: Iterator[Float] = new ArrayOps.ArrayIterator[Float](array) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[Float, S]): S with EfficientSplit = ( + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[Float, S]): S & EfficientSplit = ( if(shape.shape == StepperShape.ReferenceShape) AnyStepper.ofParDoubleStepper(new WidenedFloatArrayStepper(array, 0, array.length)) else new WidenedFloatArrayStepper(array, 0, array.length) - ).asInstanceOf[S with EfficientSplit] + ).asInstanceOf[S & EfficientSplit] } @SerialVersionUID(3L) @@ -325,11 +325,11 @@ object ArraySeq extends StrictOptimizedClassTagSeqFactory[ArraySeq] { self => case _ => super.equals(that) } override def iterator: Iterator[Double] = new ArrayOps.ArrayIterator[Double](array) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[Double, S]): S with EfficientSplit = ( + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[Double, S]): S & EfficientSplit = ( if(shape.shape == StepperShape.ReferenceShape) AnyStepper.ofParDoubleStepper(new DoubleArrayStepper(array, 0, array.length)) else new DoubleArrayStepper(array, 0, array.length) - ).asInstanceOf[S with EfficientSplit] + ).asInstanceOf[S & EfficientSplit] } @SerialVersionUID(3L) @@ -345,8 +345,8 @@ object ArraySeq extends StrictOptimizedClassTagSeqFactory[ArraySeq] { self => case _ => super.equals(that) } override def iterator: Iterator[Boolean] = new ArrayOps.ArrayIterator[Boolean](array) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[Boolean, S]): S with EfficientSplit = - new BoxedBooleanArrayStepper(array, 0, array.length).asInstanceOf[S with EfficientSplit] + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[Boolean, S]): S & EfficientSplit = + new BoxedBooleanArrayStepper(array, 0, array.length).asInstanceOf[S & EfficientSplit] } @SerialVersionUID(3L) @@ -362,7 +362,7 @@ object ArraySeq extends StrictOptimizedClassTagSeqFactory[ArraySeq] { self => case _ => super.equals(that) } override def iterator: Iterator[Unit] = new ArrayOps.ArrayIterator[Unit](array) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[Unit, S]): S with EfficientSplit = - new ObjectArrayStepper[AnyRef](array.asInstanceOf[Array[AnyRef]], 0, array.length).asInstanceOf[S with EfficientSplit] + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[Unit, S]): S & EfficientSplit = + new ObjectArrayStepper[AnyRef](array.asInstanceOf[Array[AnyRef]], 0, array.length).asInstanceOf[S & EfficientSplit] } } diff --git a/library/src/scala/collection/mutable/BitSet.scala b/library/src/scala/collection/mutable/BitSet.scala index cc622acbe566..be3fcab41614 100644 --- a/library/src/scala/collection/mutable/BitSet.scala +++ b/library/src/scala/collection/mutable/BitSet.scala @@ -268,7 +268,7 @@ class BitSet(protected[collection] final var elems: Array[Long]) case other => super.subtractAll(other) } - protected[this] def writeReplace(): AnyRef = new BitSet.SerializationProxy(this) + protected def writeReplace(): AnyRef = new BitSet.SerializationProxy(this) override def diff(that: collection.Set[Int]): BitSet = that match { case bs: collection.BitSet => @@ -390,6 +390,6 @@ object BitSet extends SpecificIterableFactory[Int, BitSet] { @SerialVersionUID(3L) private final class SerializationProxy(coll: BitSet) extends scala.collection.BitSet.SerializationProxy(coll) { - protected[this] def readResolve(): Any = BitSet.fromBitMaskNoCopy(elems) + protected def readResolve(): Any = BitSet.fromBitMaskNoCopy(elems) } } diff --git a/library/src/scala/collection/mutable/Buffer.scala b/library/src/scala/collection/mutable/Buffer.scala index bfed8dd0add4..116dd6a8bc24 100644 --- a/library/src/scala/collection/mutable/Buffer.scala +++ b/library/src/scala/collection/mutable/Buffer.scala @@ -248,7 +248,7 @@ trait Buffer[A] } @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix = "Buffer" + override protected def stringPrefix = "Buffer" } trait IndexedBuffer[A] extends IndexedSeq[A] diff --git a/library/src/scala/collection/mutable/Builder.scala b/library/src/scala/collection/mutable/Builder.scala index 715ae02bc519..54f8f331edd1 100644 --- a/library/src/scala/collection/mutable/Builder.scala +++ b/library/src/scala/collection/mutable/Builder.scala @@ -68,7 +68,7 @@ trait Builder[-A, +To] extends Growable[A] { self: Builder[A, To]^ => * @param coll the collection which serves as a hint for the result's size. * @param delta a correction to add to the `coll.size` to produce the size hint (zero if omitted). */ - final def sizeHint(coll: scala.collection.IterableOnce[_]^, delta: Int = 0): Unit = + final def sizeHint(coll: scala.collection.IterableOnce[?]^, delta: Int = 0): Unit = coll.knownSize match { case -1 => case sz => sizeHint(0 max sz + delta) @@ -87,7 +87,7 @@ trait Builder[-A, +To] extends Growable[A] { self: Builder[A, To]^ => * than collection's size are reduced. */ // should probably be `boundingColl: IterableOnce[_]`, but binary compatibility - final def sizeHintBounded(size: Int, boundingColl: scala.collection.Iterable[_]^): Unit = { + final def sizeHintBounded(size: Int, boundingColl: scala.collection.Iterable[?]^): Unit = { val s = boundingColl.knownSize if (s != -1) { sizeHint(scala.math.min(s, size)) diff --git a/library/src/scala/collection/mutable/CheckedIndexedSeqView.scala b/library/src/scala/collection/mutable/CheckedIndexedSeqView.scala index 2c9d002ac88e..ba9af308e8c7 100644 --- a/library/src/scala/collection/mutable/CheckedIndexedSeqView.scala +++ b/library/src/scala/collection/mutable/CheckedIndexedSeqView.scala @@ -45,7 +45,7 @@ private[mutable] object CheckedIndexedSeqView { @SerialVersionUID(3L) private[mutable] class CheckedIterator[A](self: IndexedSeqView[A]^, mutationCount: => Int) extends IndexedSeqView.IndexedSeqViewIterator[A](self) { - private[this] val expectedCount = mutationCount + private val expectedCount = mutationCount override def hasNext: Boolean = { MutationTracker.checkMutationsForIteration(expectedCount, mutationCount) super.hasNext @@ -55,7 +55,7 @@ private[mutable] object CheckedIndexedSeqView { @SerialVersionUID(3L) private[mutable] class CheckedReverseIterator[A](self: IndexedSeqView[A]^, mutationCount: => Int) extends IndexedSeqView.IndexedSeqViewReverseIterator[A](self) { - private[this] val expectedCount = mutationCount + private val expectedCount = mutationCount override def hasNext: Boolean = { MutationTracker.checkMutationsForIteration(expectedCount, mutationCount) super.hasNext diff --git a/library/src/scala/collection/mutable/CollisionProofHashMap.scala b/library/src/scala/collection/mutable/CollisionProofHashMap.scala index 69f2ac4af202..e2fb03cf14a5 100644 --- a/library/src/scala/collection/mutable/CollisionProofHashMap.scala +++ b/library/src/scala/collection/mutable/CollisionProofHashMap.scala @@ -41,30 +41,30 @@ final class CollisionProofHashMap[K, V](initialCapacity: Int, loadFactor: Double with StrictOptimizedIterableOps[(K, V), Iterable, CollisionProofHashMap[K, V]] with StrictOptimizedMapOps[K, V, Map, CollisionProofHashMap[K, V]] { //-- - private[this] final def sortedMapFactory: SortedMapFactory[CollisionProofHashMap] = CollisionProofHashMap + private final def sortedMapFactory: SortedMapFactory[CollisionProofHashMap] = CollisionProofHashMap - def this()(implicit ordering: Ordering[K]) = this(CollisionProofHashMap.defaultInitialCapacity, CollisionProofHashMap.defaultLoadFactor)(ordering) + def this()(implicit ordering: Ordering[K]) = this(CollisionProofHashMap.defaultInitialCapacity, CollisionProofHashMap.defaultLoadFactor)(using ordering) import CollisionProofHashMap.Node - private[this] type RBNode = CollisionProofHashMap.RBNode[K, V] - private[this] type LLNode = CollisionProofHashMap.LLNode[K, V] + private type RBNode = CollisionProofHashMap.RBNode[K, V] + private type LLNode = CollisionProofHashMap.LLNode[K, V] /** The actual hash table. */ - private[this] var table: Array[Node | Null] = new Array[Node | Null](tableSizeFor(initialCapacity)) + private var table: Array[Node | Null] = new Array[Node | Null](tableSizeFor(initialCapacity)) /** The next size value at which to resize (capacity * load factor). */ - private[this] var threshold: Int = newThreshold(table.length) + private var threshold: Int = newThreshold(table.length) - private[this] var contentSize = 0 + private var contentSize = 0 override def size: Int = contentSize - @`inline` private[this] final def computeHash(o: K): Int = { + @inline private final def computeHash(o: K): Int = { val h = if(o.asInstanceOf[AnyRef] eq null) 0 else o.hashCode h ^ (h >>> 16) } - @`inline` private[this] final def index(hash: Int) = hash & (table.length - 1) + @inline private final def index(hash: Int) = hash & (table.length - 1) override protected def fromSpecific(coll: (IterableOnce[(K, V)] @uncheckedVariance)^): CollisionProofHashMap[K, V] @uncheckedVariance = CollisionProofHashMap.from(coll) override protected def newSpecificBuilder: Builder[(K, V), CollisionProofHashMap[K, V]] @uncheckedVariance = CollisionProofHashMap.newBuilder[K, V] @@ -98,7 +98,7 @@ final class CollisionProofHashMap[K, V](initialCapacity: Int, loadFactor: Double } } - @`inline` private[this] def findNode(elem: K): Node | Null = { + @`inline` private def findNode(elem: K): Node | Null = { val hash = computeHash(elem) table(index(hash)) match { case null => null @@ -124,14 +124,14 @@ final class CollisionProofHashMap[K, V](initialCapacity: Int, loadFactor: Double def addOne(elem: (K, V)): this.type = { put0(elem._1, elem._2, getOld = false); this } - @`inline` private[this] def put0(key: K, value: V, getOld: Boolean): Some[V] | Null = { + @`inline` private def put0(key: K, value: V, getOld: Boolean): Some[V] | Null = { if(contentSize + 1 >= threshold) growTable(table.length * 2) val hash = computeHash(key) val idx = index(hash) put0(key, value, getOld, hash, idx) } - private[this] def put0(key: K, value: V, getOld: Boolean, hash: Int, idx: Int): Some[V] | Null = { + private def put0(key: K, value: V, getOld: Boolean, hash: Int, idx: Int): Some[V] | Null = { val res = table(idx) match { case n: RBNode @uc => insert(n, idx, key, hash, value) @@ -166,7 +166,7 @@ final class CollisionProofHashMap[K, V](initialCapacity: Int, loadFactor: Double if(res) Some(null.asInstanceOf[V]) else null //TODO } - private[this] def treeify(old: LLNode, idx: Int): Unit = { + private def treeify(old: LLNode, idx: Int): Unit = { table(idx) = CollisionProofHashMap.leaf(old.key, old.hash, old.value, red = false, null) var n: LLNode | Null = old.next while(n ne null) { @@ -182,7 +182,7 @@ final class CollisionProofHashMap[K, V](initialCapacity: Int, loadFactor: Double } // returns the old value or Statics.pfMarker if not found - private[this] def remove0(elem: K) : Any = { + private def remove0(elem: K) : Any = { val hash = computeHash(elem) val idx = index(hash) table(idx) match { @@ -213,13 +213,13 @@ final class CollisionProofHashMap[K, V](initialCapacity: Int, loadFactor: Double } } - private[this] abstract class MapIterator[R] extends AbstractIterator[R] { - protected[this] def extract(node: LLNode): R - protected[this] def extract(node: RBNode): R + private abstract class MapIterator[R] extends AbstractIterator[R] { + protected def extract(node: LLNode): R + protected def extract(node: RBNode): R - private[this] var i = 0 - private[this] var node: Node | Null = null - private[this] val len = table.length + private var i = 0 + private var node: Node | Null = null + private val len = table.length def hasNext: Boolean = { if(node ne null) true @@ -258,20 +258,20 @@ final class CollisionProofHashMap[K, V](initialCapacity: Int, loadFactor: Double override def keysIterator: Iterator[K] = { if (isEmpty) Iterator.empty else new MapIterator[K] { - protected[this] def extract(node: LLNode) = node.key - protected[this] def extract(node: RBNode) = node.key + protected def extract(node: LLNode) = node.key + protected def extract(node: RBNode) = node.key } } override def iterator: Iterator[(K, V)] = { if (isEmpty) Iterator.empty else new MapIterator[(K, V)] { - protected[this] def extract(node: LLNode) = (node.key, node.value) - protected[this] def extract(node: RBNode) = (node.key, node.value) + protected def extract(node: LLNode) = (node.key, node.value) + protected def extract(node: RBNode) = (node.key, node.value) } } - private[this] def growTable(newlen: Int) = { + private def growTable(newlen: Int) = { var oldlen = table.length table = java.util.Arrays.copyOf(table, newlen) threshold = newThreshold(table.length) @@ -286,18 +286,18 @@ final class CollisionProofHashMap[K, V](initialCapacity: Int, loadFactor: Double } } - @`inline` private[this] def reallocTable(newlen: Int) = { + @`inline` private def reallocTable(newlen: Int) = { table = new Array[Node | Null](newlen) threshold = newThreshold(table.length) } - @`inline` private[this] def splitBucket(tree: Node | Null, lowBucket: Int, highBucket: Int, mask: Int): Unit = tree match { + @`inline` private def splitBucket(tree: Node | Null, lowBucket: Int, highBucket: Int, mask: Int): Unit = tree match { case t: LLNode @uc => splitBucket(t, lowBucket, highBucket, mask) case t: RBNode @uc => splitBucket(t, lowBucket, highBucket, mask) case null => } - private[this] def splitBucket(list: LLNode, lowBucket: Int, highBucket: Int, mask: Int): Unit = { + private def splitBucket(list: LLNode, lowBucket: Int, highBucket: Int, mask: Int): Unit = { val preLow: LLNode = new LLNode(null.asInstanceOf[K], 0, null.asInstanceOf[V], null) val preHigh: LLNode = new LLNode(null.asInstanceOf[K], 0, null.asInstanceOf[V], null) //preLow.next = null @@ -324,7 +324,7 @@ final class CollisionProofHashMap[K, V](initialCapacity: Int, loadFactor: Double } } - private[this] def splitBucket(tree: RBNode, lowBucket: Int, highBucket: Int, mask: Int): Unit = { + private def splitBucket(tree: RBNode, lowBucket: Int, highBucket: Int, mask: Int): Unit = { var lowCount, highCount = 0 tree.foreachNode((n: RBNode) => if((n.hash & mask) != 0) highCount += 1 else lowCount += 1) if(highCount != 0) { @@ -338,10 +338,10 @@ final class CollisionProofHashMap[K, V](initialCapacity: Int, loadFactor: Double } } - private[this] def tableSizeFor(capacity: Int) = + private def tableSizeFor(capacity: Int) = (Integer.highestOneBit((capacity-1).max(4))*2).min(1 << 30) - private[this] def newThreshold(size: Int) = (size.toDouble * loadFactor).toInt + private def newThreshold(size: Int) = (size.toDouble * loadFactor).toInt override def clear(): Unit = { java.util.Arrays.fill(table.asInstanceOf[Array[AnyRef]], null) @@ -385,9 +385,9 @@ final class CollisionProofHashMap[K, V](initialCapacity: Int, loadFactor: Double } } - protected[this] def writeReplace(): AnyRef = new DefaultSerializationProxy(new CollisionProofHashMap.DeserializationFactory[K, V](table.length, loadFactor, ordering), this) + protected def writeReplace(): AnyRef = new DefaultSerializationProxy(new CollisionProofHashMap.DeserializationFactory[K, V](table.length, loadFactor, ordering), this) - override protected[this] def className = "CollisionProofHashMap" + override protected def className = "CollisionProofHashMap" override def getOrElseUpdate(key: K, defaultValue: => V): V = { val hash = computeHash(key) @@ -463,22 +463,22 @@ final class CollisionProofHashMap[K, V](initialCapacity: Int, loadFactor: Double ///////////////////// RedBlackTree code derived from mutable.RedBlackTree: - @`inline` private[this] def isRed(node: RBNode | Null) = (node ne null) && node.red - @`inline` private[this] def isBlack(node: RBNode | Null) = (node eq null) || !node.red + @`inline` private def isRed(node: RBNode | Null) = (node ne null) && node.red + @`inline` private def isBlack(node: RBNode | Null) = (node eq null) || !node.red - @unused @`inline` private[this] def compare(key: K, hash: Int, node: LLNode): Int = { + @unused @`inline` private def compare(key: K, hash: Int, node: LLNode): Int = { val i = hash - node.hash if(i != 0) i else ordering.compare(key, node.key) } - @`inline` private[this] def compare(key: K, hash: Int, node: RBNode): Int = { + @`inline` private def compare(key: K, hash: Int, node: RBNode): Int = { /*val i = hash - node.hash if(i != 0) i else*/ ordering.compare(key, node.key) } // ---- insertion ---- - @tailrec private[this] final def insertIntoExisting(_root: RBNode, bucket: Int, key: K, hash: Int, value: V, x: RBNode): Boolean = { + @tailrec private final def insertIntoExisting(_root: RBNode, bucket: Int, key: K, hash: Int, value: V, x: RBNode): Boolean = { val cmp = compare(key, hash, x) if(cmp == 0) { x.value = value @@ -495,14 +495,14 @@ final class CollisionProofHashMap[K, V](initialCapacity: Int, loadFactor: Double } } - private[this] final def insert(tree: RBNode | Null, bucket: Int, key: K, hash: Int, value: V): Boolean = { + private final def insert(tree: RBNode | Null, bucket: Int, key: K, hash: Int, value: V): Boolean = { if(tree eq null) { table(bucket) = CollisionProofHashMap.leaf(key, hash, value, red = false, null) true } else insertIntoExisting(tree, bucket, key, hash, value, tree) } - private[this] def fixAfterInsert(_root: RBNode, node: RBNode): RBNode = { + private def fixAfterInsert(_root: RBNode, node: RBNode): RBNode = { var root = _root var z = node while (isRed(z.parent)) { @@ -547,7 +547,7 @@ final class CollisionProofHashMap[K, V](initialCapacity: Int, loadFactor: Double // ---- deletion ---- // returns the old value or Statics.pfMarker if not found - private[this] def delete(_root: RBNode, bucket: Int, key: K, hash: Int): Any = { + private def delete(_root: RBNode, bucket: Int, key: K, hash: Int): Any = { var root = _root val z = root.getNode(key, hash: Int) if (z ne null) { @@ -591,7 +591,7 @@ final class CollisionProofHashMap[K, V](initialCapacity: Int, loadFactor: Double } else Statics.pfMarker } - private[this] def fixAfterDelete(_root: RBNode, node: RBNode | Null, parent: RBNode | Null): RBNode = { + private def fixAfterDelete(_root: RBNode, node: RBNode | Null, parent: RBNode | Null): RBNode = { var root = _root var x = node var xParent = parent @@ -657,7 +657,7 @@ final class CollisionProofHashMap[K, V](initialCapacity: Int, loadFactor: Double // ---- helpers ---- - @`inline` private[this] def rotateLeft(_root: RBNode, x: RBNode): RBNode = { + @`inline` private def rotateLeft(_root: RBNode, x: RBNode): RBNode = { var root = _root val y = x.right.nn x.right = y.left @@ -675,7 +675,7 @@ final class CollisionProofHashMap[K, V](initialCapacity: Int, loadFactor: Double root } - @`inline` private[this] def rotateRight(_root: RBNode, x: RBNode): RBNode = { + @`inline` private def rotateRight(_root: RBNode, x: RBNode): RBNode = { var root = _root val y = x.left.nn x.left = y.right @@ -697,7 +697,7 @@ final class CollisionProofHashMap[K, V](initialCapacity: Int, loadFactor: Double * Transplant the node `from` to the place of node `to`. This is done by setting `from` as a child of `to`'s previous * parent and setting `from`'s parent to the `to`'s previous parent. The children of `from` are left unchanged. */ - private[this] def transplant(_root: RBNode, to: RBNode, from: RBNode): RBNode = { + private def transplant(_root: RBNode, to: RBNode, from: RBNode): RBNode = { var root = _root if (to.parent eq null) root = from else if (to eq to.parent.left) to.parent.left = from @@ -768,7 +768,7 @@ object CollisionProofHashMap extends SortedMapFactory[CollisionProofHashMap] { final def defaultInitialCapacity: Int = 16 @SerialVersionUID(3L) - private final class DeserializationFactory[K, V](val tableLength: Int, val loadFactor: Double, val ordering: Ordering[K]) extends Factory[(K, V), CollisionProofHashMap[K, V]] with Serializable { + private final class DeserializationFactory[K, V](val tableLength: Int, val loadFactor: Double, val ordering: Ordering[K]) extends Factory[(K, V), CollisionProofHashMap[K, V]], Serializable { def fromSpecific(it: IterableOnce[(K, V)]^): CollisionProofHashMap[K, V] = new CollisionProofHashMap[K, V](tableLength, loadFactor)(using ordering) ++= it def newBuilder: Builder[(K, V), CollisionProofHashMap[K, V]] = CollisionProofHashMap.newBuilder(tableLength, loadFactor)(using ordering) } @@ -854,7 +854,7 @@ object CollisionProofHashMap extends SortedMapFactory[CollisionProofHashMap] { } private final class RBNodesIterator[A, B](tree: RBNode[A, B] | Null)(implicit @unused ord: Ordering[A]) extends AbstractIterator[RBNode[A, B]] { - private[this] var nextNode: RBNode[A, B] | Null = if(tree eq null) null else minNodeNonNull(tree) + private var nextNode: RBNode[A, B] | Null = if(tree eq null) null else minNodeNonNull(tree) def hasNext: Boolean = nextNode ne null @@ -872,7 +872,7 @@ object CollisionProofHashMap extends SortedMapFactory[CollisionProofHashMap] { private final class LLNode[K, V](var key: K, var hash: Int, var value: V, @annotation.stableNull var next: LLNode[K, V] | Null) extends Node { override def toString = s"LLNode($key, $value, $hash) -> $next" - private[this] def eq(a: Any, b: Any): Boolean = + private def eq(a: Any, b: Any): Boolean = if(a.asInstanceOf[AnyRef] eq null) b.asInstanceOf[AnyRef] eq null else a.asInstanceOf[AnyRef].equals(b) @tailrec def getNode(k: K, h: Int)(implicit ord: Ordering[K]): LLNode[K, V] | Null = { diff --git a/library/src/scala/collection/mutable/HashMap.scala b/library/src/scala/collection/mutable/HashMap.scala index 0e3c8e7ce2a5..e7451b02bede 100644 --- a/library/src/scala/collection/mutable/HashMap.scala +++ b/library/src/scala/collection/mutable/HashMap.scala @@ -53,12 +53,12 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) import HashMap.Node /** The actual hash table. */ - private[this] var table = new Array[Node[K, V] | Null](tableSizeFor(initialCapacity)) + private var table = new Array[Node[K, V] | Null](tableSizeFor(initialCapacity)) /** The next size value at which to resize (capacity * load factor). */ - private[this] var threshold: Int = newThreshold(table.length) + private var threshold: Int = newThreshold(table.length) - private[this] var contentSize = 0 + private var contentSize = 0 override def size: Int = contentSize @@ -66,7 +66,7 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) @`inline` private[collection] def unimproveHash(improvedHash: Int): Int = improveHash(improvedHash) /** Computes the improved hash of an original (`any.##`) hash. */ - @`inline` private[this] def improveHash(originalHash: Int): Int = { + @`inline` private def improveHash(originalHash: Int): Int = { // Improve the hash by xoring the high 16 bits into the low 16 bits just in case entropy is skewed towards the // high-value bits. We only use the lowest bits to determine the hash bucket. This is the same improvement // algorithm as in java.util.HashMap. @@ -78,13 +78,13 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) } /** Computes the improved hash of this key */ - @`inline` private[this] def computeHash(o: K): Int = improveHash(o.##) + @`inline` private def computeHash(o: K): Int = improveHash(o.##) - @`inline` private[this] def index(hash: Int) = hash & (table.length - 1) + @`inline` private def index(hash: Int) = hash & (table.length - 1) override def contains(key: K): Boolean = findNode(key) ne null - @`inline` private[this] def findNode(key: K): Node[K, V] | Null = { + @`inline` private def findNode(key: K): Node[K, V] | Null = { val hash = computeHash(key) table(index(hash)) match { case null => null @@ -131,7 +131,7 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) // Override updateWith for performance, so we can do the update while hashing // the input key only once and performing one lookup into the hash table override def updateWith(key: K)(remappingFunction: Option[V] => Option[V]): Option[V] = { - if (getClass != classOf[HashMap[_, _]]) { + if (getClass != classOf[HashMap[?, ?]]) { // subclasses of HashMap might customise `get` ... super.updateWith(key)(remappingFunction) } else { @@ -227,13 +227,13 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) * @param hash the **improved** hashcode of `key` (see computeHash) * @param getOld if true, then the previous value for `key` will be returned, otherwise, false */ - private[this] def put0(key: K, value: V, hash: Int, getOld: Boolean): Some[V] | Null = { + private def put0(key: K, value: V, hash: Int, getOld: Boolean): Some[V] | Null = { if(contentSize + 1 >= threshold) growTable(table.length * 2) val idx = index(hash) put0(key, value, getOld, hash, idx) } - private[this] def put0(key: K, value: V, getOld: Boolean): Some[V] | Null = { + private def put0(key: K, value: V, getOld: Boolean): Some[V] | Null = { if(contentSize + 1 >= threshold) growTable(table.length * 2) val hash = computeHash(key) val idx = index(hash) @@ -241,7 +241,7 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) } - private[this] def put0(key: K, value: V, getOld: Boolean, hash: Int, idx: Int): Some[V] | Null = { + private def put0(key: K, value: V, getOld: Boolean, hash: Int, idx: Int): Some[V] | Null = { table(idx) match { case null => table(idx) = new Node[K, V](key, hash, value, null) @@ -272,7 +272,7 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) * @param hash the **improved** hashcode of `element` (see computeHash) * @return the node that contained element if it was present, otherwise null */ - private[this] def remove0(elem: K, hash: Int) : Node[K, V] | Null = { + private def remove0(elem: K, hash: Int) : Node[K, V] | Null = { val idx = index(hash) table(idx) match { case null => null @@ -298,12 +298,12 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) } } - private[this] abstract class HashMapIterator[A] extends AbstractIterator[A] { - private[this] var i = 0 - private[this] var node: Node[K, V] | Null = null - private[this] val len = table.length + private abstract class HashMapIterator[A] extends AbstractIterator[A] { + private var i = 0 + private var node: Node[K, V] | Null = null + private val len = table.length - protected[this] def extract(nd: Node[K, V]): A + protected def extract(nd: Node[K, V]): A def hasNext: Boolean = { if(node ne null) true @@ -329,19 +329,19 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) override def iterator: Iterator[(K, V)] = if(size == 0) Iterator.empty else new HashMapIterator[(K, V)] { - protected[this] def extract(nd: Node[K, V]) = (nd.key, nd.value) + protected def extract(nd: Node[K, V]) = (nd.key, nd.value) } override def keysIterator: Iterator[K] = if(size == 0) Iterator.empty else new HashMapIterator[K] { - protected[this] def extract(nd: Node[K, V]) = nd.key + protected def extract(nd: Node[K, V]) = nd.key } override def valuesIterator: Iterator[V] = if(size == 0) Iterator.empty else new HashMapIterator[V] { - protected[this] def extract(nd: Node[K, V]) = nd.value + protected def extract(nd: Node[K, V]) = nd.value } @@ -349,15 +349,15 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) private[collection] def nodeIterator: Iterator[Node[K, V]] = if(size == 0) Iterator.empty else new HashMapIterator[Node[K, V]] { - protected[this] def extract(nd: Node[K, V]) = nd + protected def extract(nd: Node[K, V]) = nd } - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[(K, V), S]): S with EfficientSplit = + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[(K, V), S]): S & EfficientSplit = shape. parUnbox(new convert.impl.AnyTableStepper[(K, V), Node[K, V]](size, table, _.next.nn, node => (node.key, node.value), 0, table.length)). - asInstanceOf[S with EfficientSplit] + asInstanceOf[S & EfficientSplit] - override def keyStepper[S <: Stepper[_]](implicit shape: StepperShape[K, S]): S with EfficientSplit = { + override def keyStepper[S <: Stepper[?]](implicit shape: StepperShape[K, S]): S & EfficientSplit = { import convert.impl._ val s = shape.shape match { case StepperShape.IntShape => new IntTableStepper[Node[K, V]] (size, table, _.next.nn, _.key.asInstanceOf[Int], 0, table.length) @@ -365,10 +365,10 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) case StepperShape.DoubleShape => new DoubleTableStepper[Node[K, V]](size, table, _.next.nn, _.key.asInstanceOf[Double], 0, table.length) case _ => shape.parUnbox(new AnyTableStepper[K, Node[K, V]](size, table, _.next.nn, _.key, 0, table.length)) } - s.asInstanceOf[S with EfficientSplit] + s.asInstanceOf[S & EfficientSplit] } - override def valueStepper[S <: Stepper[_]](implicit shape: StepperShape[V, S]): S with EfficientSplit = { + override def valueStepper[S <: Stepper[?]](implicit shape: StepperShape[V, S]): S & EfficientSplit = { import convert.impl._ val s = shape.shape match { case StepperShape.IntShape => new IntTableStepper[Node[K, V]] (size, table, _.next.nn, _.value.asInstanceOf[Int], 0, table.length) @@ -376,10 +376,10 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) case StepperShape.DoubleShape => new DoubleTableStepper[Node[K, V]](size, table, _.next.nn, _.value.asInstanceOf[Double], 0, table.length) case _ => shape.parUnbox(new AnyTableStepper[V, Node[K, V]](size, table, _.next.nn, _.value, 0, table.length)) } - s.asInstanceOf[S with EfficientSplit] + s.asInstanceOf[S & EfficientSplit] } - private[this] def growTable(newlen: Int) = { + private def growTable(newlen: Int) = { if (newlen < 0) throw new RuntimeException(s"new HashMap table size $newlen exceeds maximum") var oldlen = table.length @@ -426,10 +426,10 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) } } - private[this] def tableSizeFor(capacity: Int) = + private def tableSizeFor(capacity: Int) = (Integer.highestOneBit((capacity-1).max(4))*2).min(1 << 30) - private[this] def newThreshold(size: Int) = (size.toDouble * loadFactor).toInt + private def newThreshold(size: Int) = (size.toDouble * loadFactor).toInt override def clear(): Unit = { java.util.Arrays.fill(table.asInstanceOf[Array[AnyRef]], null) @@ -448,7 +448,7 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) } override def getOrElse[V1 >: V](key: K, default: => V1): V1 = { - if (getClass != classOf[HashMap[_, _]]) { + if (getClass != classOf[HashMap[?, ?]]) { // subclasses of HashMap might customise `get` ... super.getOrElse(key, default) } else { @@ -459,7 +459,7 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) } override def getOrElseUpdate(key: K, defaultValue: => V): V = { - if (getClass != classOf[HashMap[_, _]]) { + if (getClass != classOf[HashMap[?, ?]]) { // subclasses of HashMap might customise `get` ... super.getOrElseUpdate(key, defaultValue) } else { @@ -522,7 +522,7 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) } } - protected[this] def writeReplace(): AnyRef = new DefaultSerializationProxy(new mutable.HashMap.DeserializationFactory[K, V](table.length, loadFactor), this) + protected def writeReplace(): AnyRef = new DefaultSerializationProxy(new mutable.HashMap.DeserializationFactory[K, V](table.length, loadFactor), this) override def filterInPlace(p: (K, V) => Boolean): this.type = { if (nonEmpty) { @@ -576,7 +576,7 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) override def mapFactory: MapFactory[HashMap] = HashMap @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix = "HashMap" + override protected def stringPrefix = "HashMap" override def hashCode: Int = { if (isEmpty) MurmurHash3.emptyMapHash @@ -584,7 +584,7 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) val tupleHashIterator = new HashMapIterator[Any] { var hash: Int = 0 override def hashCode: Int = hash - override protected[this] def extract(nd: Node[K, V]): Any = { + override protected def extract(nd: Node[K, V]): Any = { hash = MurmurHash3.tuple2Hash(unimproveHash(nd.hash), nd.value.##) this } @@ -624,12 +624,12 @@ object HashMap extends MapFactory[HashMap] { final def defaultInitialCapacity: Int = 16 @SerialVersionUID(3L) - private final class DeserializationFactory[K, V](val tableLength: Int, val loadFactor: Double) extends Factory[(K, V), HashMap[K, V]] with Serializable { + private final class DeserializationFactory[K, V](val tableLength: Int, val loadFactor: Double) extends Factory[(K, V), HashMap[K, V]], Serializable { def fromSpecific(it: IterableOnce[(K, V)]^): HashMap[K, V] = new HashMap[K, V](tableLength, loadFactor).addAll(it) def newBuilder: Builder[(K, V), HashMap[K, V]] = HashMap.newBuilder(tableLength, loadFactor) } - private[collection] final class Node[K, V](_key: K, _hash: Int, private[this] var _value: V, @annotation.stableNull private[this] var _next: Node[K, V] | Null) { + private[collection] final class Node[K, V](_key: K, _hash: Int, private var _value: V, @annotation.stableNull private var _next: Node[K, V] | Null) { def key: K = _key def hash: Int = _hash def value: V = _value diff --git a/library/src/scala/collection/mutable/HashSet.scala b/library/src/scala/collection/mutable/HashSet.scala index 5dff2155b385..1db7a19b50c3 100644 --- a/library/src/scala/collection/mutable/HashSet.scala +++ b/library/src/scala/collection/mutable/HashSet.scala @@ -48,12 +48,12 @@ final class HashSet[A](initialCapacity: Int, loadFactor: Double) * - The sum of the lengths of all buckets is equal to contentSize. */ /** The actual hash table. */ - private[this] var table = new Array[Node[A] | Null](tableSizeFor(initialCapacity)) + private var table = new Array[Node[A] | Null](tableSizeFor(initialCapacity)) /** The next size value at which to resize (capacity * load factor). */ - private[this] var threshold: Int = newThreshold(table.length) + private var threshold: Int = newThreshold(table.length) - private[this] var contentSize = 0 + private var contentSize = 0 override def size: Int = contentSize @@ -61,7 +61,7 @@ final class HashSet[A](initialCapacity: Int, loadFactor: Double) @`inline` private[collection] def unimproveHash(improvedHash: Int): Int = improveHash(improvedHash) /** Computes the improved hash of an original (`any.##`) hash. */ - private[this] def improveHash(originalHash: Int): Int = { + private def improveHash(originalHash: Int): Int = { // Improve the hash by xoring the high 16 bits into the low 16 bits just in case entropy is skewed towards the // high-value bits. We only use the lowest bits to determine the hash bucket. This is the same improvement // algorithm as in java.util.HashMap. @@ -69,13 +69,13 @@ final class HashSet[A](initialCapacity: Int, loadFactor: Double) } /** Computes the improved hash of this element */ - @`inline` private[this] def computeHash(o: A): Int = improveHash(o.##) + @`inline` private def computeHash(o: A): Int = improveHash(o.##) - @`inline` private[this] def index(hash: Int) = hash & (table.length - 1) + @`inline` private def index(hash: Int) = hash & (table.length - 1) override def contains(elem: A): Boolean = findNode(elem) ne null - @`inline` private[this] def findNode(elem: A): Node[A] | Null = { + @`inline` private def findNode(elem: A): Node[A] | Null = { val hash = computeHash(elem) table(index(hash)) match { case null => null @@ -153,7 +153,7 @@ final class HashSet[A](initialCapacity: Int, loadFactor: Double) * @param elem element to add * @param hash the **improved** hash of `elem` (see computeHash) */ - private[this] def addElem(elem: A, hash: Int) : Boolean = { + private def addElem(elem: A, hash: Int) : Boolean = { val idx = index(hash) table(idx) match { case null => @@ -175,7 +175,7 @@ final class HashSet[A](initialCapacity: Int, loadFactor: Double) true } - private[this] def remove(elem: A, hash: Int): Boolean = { + private def remove(elem: A, hash: Int): Boolean = { val idx = index(hash) table(idx) match { case null => false @@ -203,12 +203,12 @@ final class HashSet[A](initialCapacity: Int, loadFactor: Double) override def remove(elem: A) : Boolean = remove(elem, computeHash(elem)) - private[this] abstract class HashSetIterator[B] extends AbstractIterator[B] { - private[this] var i = 0 - private[this] var node: Node[A] | Null = null - private[this] val len = table.length + private abstract class HashSetIterator[B] extends AbstractIterator[B] { + private var i = 0 + private var node: Node[A] | Null = null + private val len = table.length - protected[this] def extract(nd: Node[A]): B + protected def extract(nd: Node[A]): B def hasNext: Boolean = { if(node ne null) true @@ -232,15 +232,15 @@ final class HashSet[A](initialCapacity: Int, loadFactor: Double) } override def iterator: Iterator[A] = new HashSetIterator[A] { - override protected[this] def extract(nd: Node[A]): A = nd.key + override protected def extract(nd: Node[A]): A = nd.key } /** Returns an iterator over the nodes stored in this HashSet */ private[collection] def nodeIterator: Iterator[Node[A]] = new HashSetIterator[Node[A]] { - override protected[this] def extract(nd: Node[A]): Node[A] = nd + override protected def extract(nd: Node[A]): Node[A] = nd } - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[A, S]): S with EfficientSplit = { + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[A, S]): S & EfficientSplit = { import convert.impl._ val s = shape.shape match { case StepperShape.IntShape => new IntTableStepper[Node[A]] (size, table, _.next.nn, _.key.asInstanceOf[Int], 0, table.length) @@ -248,10 +248,10 @@ final class HashSet[A](initialCapacity: Int, loadFactor: Double) case StepperShape.DoubleShape => new DoubleTableStepper[Node[A]](size, table, _.next.nn, _.key.asInstanceOf[Double], 0, table.length) case _ => shape.parUnbox(new AnyTableStepper[A, Node[A]](size, table, _.next.nn, _.key, 0, table.length)) } - s.asInstanceOf[S with EfficientSplit] + s.asInstanceOf[S & EfficientSplit] } - private[this] def growTable(newlen: Int) = { + private def growTable(newlen: Int) = { var oldlen = table.length threshold = newThreshold(newlen) if(size == 0) table = new Array[Node[A] | Null](newlen) @@ -351,10 +351,10 @@ final class HashSet[A](initialCapacity: Int, loadFactor: Double) } */ - private[this] def tableSizeFor(capacity: Int) = + private def tableSizeFor(capacity: Int) = (Integer.highestOneBit((capacity-1).max(4))*2).min(1 << 30) - private[this] def newThreshold(size: Int) = (size.toDouble * loadFactor).toInt + private def newThreshold(size: Int) = (size.toDouble * loadFactor).toInt def clear(): Unit = { java.util.Arrays.fill(table.asInstanceOf[Array[AnyRef]], null) @@ -381,9 +381,9 @@ final class HashSet[A](initialCapacity: Int, loadFactor: Double) } } - protected[this] def writeReplace(): AnyRef = new DefaultSerializationProxy(new HashSet.DeserializationFactory[A](table.length, loadFactor), this) + protected def writeReplace(): AnyRef = new DefaultSerializationProxy(new HashSet.DeserializationFactory[A](table.length, loadFactor), this) - override protected[this] def className = "HashSet" + override protected def className = "HashSet" override def hashCode: Int = { val setIterator = this.iterator @@ -392,7 +392,7 @@ final class HashSet[A](initialCapacity: Int, loadFactor: Double) else new HashSetIterator[Any] { var hash: Int = 0 override def hashCode: Int = hash - override protected[this] def extract(nd: Node[A]): Any = { + override protected def extract(nd: Node[A]): Any = { hash = unimproveHash(nd.hash) this } @@ -431,12 +431,12 @@ object HashSet extends IterableFactory[HashSet] { final def defaultInitialCapacity: Int = 16 @SerialVersionUID(3L) - private final class DeserializationFactory[A](val tableLength: Int, val loadFactor: Double) extends Factory[A, HashSet[A]] with Serializable { + private final class DeserializationFactory[A](val tableLength: Int, val loadFactor: Double) extends Factory[A, HashSet[A]], Serializable { def fromSpecific(it: IterableOnce[A]^): HashSet[A] = new HashSet[A](tableLength, loadFactor) ++= it def newBuilder: Builder[A, HashSet[A]] = HashSet.newBuilder(tableLength, loadFactor) } - private[collection] final class Node[K](_key: K, _hash: Int, @annotation.stableNull private[this] var _next: Node[K] | Null) { + private[collection] final class Node[K](_key: K, _hash: Int, @annotation.stableNull private var _next: Node[K] | Null) { def key: K = _key def hash: Int = _hash def next: Node[K] | Null = _next diff --git a/library/src/scala/collection/mutable/HashTable.scala b/library/src/scala/collection/mutable/HashTable.scala index 0d6d01837abb..14f5bc03877e 100644 --- a/library/src/scala/collection/mutable/HashTable.scala +++ b/library/src/scala/collection/mutable/HashTable.scala @@ -416,5 +416,5 @@ private[collection] object HashTable { */ private[collection] trait HashEntry[A, E <: HashEntry[A, E]] { val key: A - var next: E | Null = _ + var next: E | Null = compiletime.uninitialized } diff --git a/library/src/scala/collection/mutable/ImmutableBuilder.scala b/library/src/scala/collection/mutable/ImmutableBuilder.scala index 5c263dab8ed7..ea499628d2c2 100644 --- a/library/src/scala/collection/mutable/ImmutableBuilder.scala +++ b/library/src/scala/collection/mutable/ImmutableBuilder.scala @@ -20,7 +20,7 @@ import language.experimental.captureChecking /** * Reusable builder for immutable collections */ -abstract class ImmutableBuilder[-A, C <: IterableOnce[_]](empty: C) +abstract class ImmutableBuilder[-A, C <: IterableOnce[?]](empty: C) extends ReusableBuilder[A, C] { protected var elems: C = empty diff --git a/library/src/scala/collection/mutable/IndexedSeq.scala b/library/src/scala/collection/mutable/IndexedSeq.scala index 46dfc7e85f60..9ece635bed80 100644 --- a/library/src/scala/collection/mutable/IndexedSeq.scala +++ b/library/src/scala/collection/mutable/IndexedSeq.scala @@ -74,13 +74,13 @@ transparent trait IndexedSeqOps[A, +CC[_] <: caps.Pure, +C <: AnyRef] * * @see [[scala.collection.SeqOps.sortWith]] */ - def sortInPlaceWith(lt: (A, A) => Boolean): this.type = sortInPlace()(Ordering.fromLessThan(lt)) + def sortInPlaceWith(lt: (A, A) => Boolean): this.type = sortInPlace()(using Ordering.fromLessThan(lt)) /** Sorts this $coll in place according to the Ordering which results from transforming * an implicitly given Ordering with a transformation function. * * @see [[scala.collection.SeqOps.sortBy]] */ - def sortInPlaceBy[B](f: A => B)(implicit ord: Ordering[B]): this.type = sortInPlace()(ord on f) + def sortInPlaceBy[B](f: A => B)(implicit ord: Ordering[B]): this.type = sortInPlace()(using ord.on(f)) } diff --git a/library/src/scala/collection/mutable/LinkedHashMap.scala b/library/src/scala/collection/mutable/LinkedHashMap.scala index 8fd1f38fca5c..eda7ea733bcd 100644 --- a/library/src/scala/collection/mutable/LinkedHashMap.scala +++ b/library/src/scala/collection/mutable/LinkedHashMap.scala @@ -64,11 +64,11 @@ class LinkedHashMap[K, V] * - Every bucket is sorted in ascendant hash order * - The sum of the lengths of all buckets is equal to contentSize. */ - private[this] var table = new Array[Entry | Null](tableSizeFor(LinkedHashMap.defaultinitialSize)) + private var table = new Array[Entry | Null](tableSizeFor(LinkedHashMap.defaultinitialSize)) - private[this] var threshold: Int = newThreshold(table.length) + private var threshold: Int = newThreshold(table.length) - private[this] var contentSize = 0 + private var contentSize = 0 override def last: (K, V) = if (size > 0) (lastEntry.nn.key, lastEntry.nn.value) @@ -101,7 +101,7 @@ class LinkedHashMap[K, V] } override def contains(key: K): Boolean = { - if (getClass eq classOf[LinkedHashMap[_, _]]) + if (getClass eq classOf[LinkedHashMap[?, ?]]) findEntry(key) != null else super.contains(key) // A subclass might override `get`, use the default implementation `contains`. @@ -120,7 +120,7 @@ class LinkedHashMap[K, V] } override def getOrElse[V1 >: V](key: K, default: => V1): V1 = { - if (getClass != classOf[LinkedHashMap[_, _]]) { + if (getClass != classOf[LinkedHashMap[?, ?]]) { // subclasses of LinkedHashMap might customise `get` ... super.getOrElse(key, default) } else { @@ -131,7 +131,7 @@ class LinkedHashMap[K, V] } override def getOrElseUpdate(key: K, defaultValue: => V): V = { - if (getClass != classOf[LinkedHashMap[_, _]]) { + if (getClass != classOf[LinkedHashMap[?, ?]]) { // subclasses of LinkedHashMap might customise `get` ... super.getOrElseUpdate(key, defaultValue) } else { @@ -154,7 +154,7 @@ class LinkedHashMap[K, V] } } - private[this] def removeEntry0(elem: K): Entry | Null = removeEntry0(elem, computeHash(elem)) + private def removeEntry0(elem: K): Entry | Null = removeEntry0(elem, computeHash(elem)) /** Removes a key from this map if it exists * @@ -162,7 +162,7 @@ class LinkedHashMap[K, V] * @param hash the **improved** hashcode of `element` (see computeHash) * @return the node that contained element if it was present, otherwise null */ - private[this] def removeEntry0(elem: K, hash: Int): Entry | Null = { + private def removeEntry0(elem: K, hash: Int): Entry | Null = { val idx = index(hash) table(idx) match { case null => null @@ -191,17 +191,17 @@ class LinkedHashMap[K, V] } /** Computes the improved hash of an original (`any.##`) hash. */ - @`inline` private[this] def improveHash(originalHash: Int): Int = { + @`inline` private def improveHash(originalHash: Int): Int = { originalHash ^ (originalHash >>> 16) } @`inline` private[collection] def unimproveHash(improvedHash: Int): Int = improveHash(improvedHash) /** Computes the improved hash of this key */ - @`inline` private[this] def computeHash(o: K): Int = improveHash(o.##) + @`inline` private def computeHash(o: K): Int = improveHash(o.##) - @`inline` private[this] def index(hash: Int) = hash & (table.length - 1) + @`inline` private def index(hash: Int) = hash & (table.length - 1) - @`inline` private[this] def findEntry(key: K): Entry | Null = { + @`inline` private def findEntry(key: K): Entry | Null = { val hash = computeHash(key) table(index(hash)) match { case null => null @@ -219,8 +219,8 @@ class LinkedHashMap[K, V] this } - private[this] abstract class LinkedHashMapIterator[T] extends AbstractIterator[T] { - private[this] var cur: Entry | Null = firstEntry + private abstract class LinkedHashMapIterator[T] extends AbstractIterator[T] { + private var cur: Entry | Null = firstEntry def extract(nd: Entry): T def hasNext: Boolean = cur ne null def next(): T = @@ -256,7 +256,7 @@ class LinkedHashMap[K, V] // Override updateWith for performance, so we can do the update while hashing // the input key only once and performing one lookup into the hash table override def updateWith(key: K)(remappingFunction: Option[V] => Option[V]): Option[V] = { - if (getClass != classOf[LinkedHashMap[_, _]]) { + if (getClass != classOf[LinkedHashMap[?, ?]]) { // subclasses of LinkedHashMap might customise `get` ... super.updateWith(key)(remappingFunction) } else { @@ -341,16 +341,16 @@ class LinkedHashMap[K, V] lastEntry = null } - private[this] def tableSizeFor(capacity: Int) = + private def tableSizeFor(capacity: Int) = (Integer.highestOneBit((capacity - 1).max(4)) * 2).min(1 << 30) - private[this] def newThreshold(size: Int) = (size.toDouble * LinkedHashMap.defaultLoadFactor).toInt + private def newThreshold(size: Int) = (size.toDouble * LinkedHashMap.defaultLoadFactor).toInt /*create a new entry. If table is empty(firstEntry is null), then the * new entry will be the firstEntry. If not, just set the new entry to * be the lastEntry. * */ - private[this] def createNewEntry(key: K, hash: Int, value: V): Entry = { + private def createNewEntry(key: K, hash: Int, value: V): Entry = { val e = new Entry(key, hash, value) if (firstEntry eq null) firstEntry = e else { @@ -362,7 +362,7 @@ class LinkedHashMap[K, V] } /** Delete the entry from the LinkedHashMap, set the `earlier` and `later` pointers correctly */ - private[this] def deleteEntry(e: Entry): Unit = { + private def deleteEntry(e: Entry): Unit = { if (e.earlier eq null) firstEntry = e.later else e.earlier.nn.later = e.later if (e.later eq null) lastEntry = e.earlier @@ -372,14 +372,14 @@ class LinkedHashMap[K, V] e.next = null } - private[this] def put0(key: K, value: V, getOld: Boolean): Some[V] | Null = { + private def put0(key: K, value: V, getOld: Boolean): Some[V] | Null = { if (contentSize + 1 >= threshold) growTable(table.length * 2) val hash = computeHash(key) val idx = index(hash) put0(key, value, getOld, hash, idx) } - private[this] def put0(key: K, value: V, getOld: Boolean, hash: Int, idx: Int): Some[V] | Null = { + private def put0(key: K, value: V, getOld: Boolean, hash: Int, idx: Int): Some[V] | Null = { table(idx) match { case null => table(idx) = createNewEntry(key, hash, value) @@ -408,7 +408,7 @@ class LinkedHashMap[K, V] null } - private[this] def growTable(newlen: Int): Unit = { + private def growTable(newlen: Int): Unit = { if (newlen < 0) throw new RuntimeException(s"new hash table size $newlen exceeds maximum") var oldlen = table.length @@ -470,7 +470,7 @@ class LinkedHashMap[K, V] } } @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix = "LinkedHashMap" + override protected def stringPrefix = "LinkedHashMap" } /** $factoryInfo diff --git a/library/src/scala/collection/mutable/LinkedHashSet.scala b/library/src/scala/collection/mutable/LinkedHashSet.scala index e31cdceb0053..803af05c54c5 100644 --- a/library/src/scala/collection/mutable/LinkedHashSet.scala +++ b/library/src/scala/collection/mutable/LinkedHashSet.scala @@ -58,11 +58,11 @@ class LinkedHashSet[A] * - Every bucket is sorted in ascendant hash order * - The sum of the lengths of all buckets is equal to contentSize. */ - private[this] var table = new Array[Entry | Null](tableSizeFor(LinkedHashSet.defaultinitialSize)) + private var table = new Array[Entry | Null](tableSizeFor(LinkedHashSet.defaultinitialSize)) - private[this] var threshold: Int = newThreshold(table.length) + private var threshold: Int = newThreshold(table.length) - private[this] var contentSize = 0 + private var contentSize = 0 override def last: A = if (size > 0) lastEntry.nn.key @@ -109,8 +109,8 @@ class LinkedHashSet[A] override def remove(elem: A): Boolean = remove0(elem, computeHash(elem)) - private[this] abstract class LinkedHashSetIterator[T] extends AbstractIterator[T] { - private[this] var cur: Entry | Null = firstEntry + private abstract class LinkedHashSetIterator[T] extends AbstractIterator[T] { + private var cur: Entry | Null = firstEntry def extract(nd: Entry): T def hasNext: Boolean = cur ne null def next(): T = @@ -141,23 +141,23 @@ class LinkedHashSet[A] lastEntry = null } - private[this] def tableSizeFor(capacity: Int) = + private def tableSizeFor(capacity: Int) = (Integer.highestOneBit((capacity - 1).max(4)) * 2).min(1 << 30) - private[this] def newThreshold(size: Int) = (size.toDouble * LinkedHashSet.defaultLoadFactor).toInt + private def newThreshold(size: Int) = (size.toDouble * LinkedHashSet.defaultLoadFactor).toInt - @`inline` private[this] def improveHash(originalHash: Int): Int = { + @`inline` private def improveHash(originalHash: Int): Int = { originalHash ^ (originalHash >>> 16) } @`inline` private[collection] def unimproveHash(improvedHash: Int): Int = improveHash(improvedHash) /** Computes the improved hash of this key */ - @`inline` private[this] def computeHash(o: A): Int = improveHash(o.##) + @`inline` private def computeHash(o: A): Int = improveHash(o.##) - @`inline` private[this] def index(hash: Int) = hash & (table.length - 1) + @`inline` private def index(hash: Int) = hash & (table.length - 1) - @`inline` private[this] def findEntry(key: A): Entry | Null = { + @`inline` private def findEntry(key: A): Entry | Null = { val hash = computeHash(key) table(index(hash)) match { case null => null @@ -169,7 +169,7 @@ class LinkedHashSet[A] * new entry will be the firstEntry. If not, just set the new entry to * be the lastEntry. * */ - private[this] def createNewEntry(key: A, hash: Int): Entry = { + private def createNewEntry(key: A, hash: Int): Entry = { val e = new Entry(key, hash) if (firstEntry eq null) firstEntry = e else { @@ -181,7 +181,7 @@ class LinkedHashSet[A] } /** Delete the entry from the LinkedHashSet, set the `earlier` and `later` pointers correctly */ - private[this] def deleteEntry(e: Entry): Unit = { + private def deleteEntry(e: Entry): Unit = { if (e.earlier eq null) firstEntry = e.later else e.earlier.later = e.later if (e.later eq null) lastEntry = e.earlier @@ -191,7 +191,7 @@ class LinkedHashSet[A] e.next = null } - private[this] def put0(elem: A, hash: Int, idx: Int): Boolean = { + private def put0(elem: A, hash: Int, idx: Int): Boolean = { table(idx) match { case null => table(idx) = createNewEntry(elem, hash) @@ -216,7 +216,7 @@ class LinkedHashSet[A] true } - private[this] def remove0(elem: A, hash: Int): Boolean = { + private def remove0(elem: A, hash: Int): Boolean = { val idx = index(hash) table(idx) match { case null => false @@ -244,7 +244,7 @@ class LinkedHashSet[A] } } - private[this] def growTable(newlen: Int): Unit = { + private def growTable(newlen: Int): Unit = { if (newlen < 0) throw new RuntimeException(s"new hash table size $newlen exceeds maximum") var oldlen = table.length @@ -308,7 +308,7 @@ class LinkedHashSet[A] } @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix: String = "LinkedHashSet" + override protected def stringPrefix: String = "LinkedHashSet" } /** $factoryInfo diff --git a/library/src/scala/collection/mutable/ListBuffer.scala b/library/src/scala/collection/mutable/ListBuffer.scala index cf0730ef0cd4..d41582a85954 100644 --- a/library/src/scala/collection/mutable/ListBuffer.scala +++ b/library/src/scala/collection/mutable/ListBuffer.scala @@ -46,13 +46,13 @@ class ListBuffer[A] with ReusableBuilder[A, immutable.List[A]] with IterableFactoryDefaults[A, ListBuffer] with DefaultSerializable { - @transient private[this] var mutationCount: Int = 0 + @transient private var mutationCount: Int = 0 private var first: List[A] = Nil @annotation.stableNull private var last0: ::[A] | Null = null // last element (`last0` just because the name `last` is already taken) - private[this] var aliased = false - private[this] var len = 0 + private var aliased = false + private var len = 0 private type Predecessor = ::[A] | Null @@ -409,7 +409,7 @@ class ListBuffer[A] override def lastOption: Option[A] = if (last0 eq null) None else Some(last0.head) @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix = "ListBuffer" + override protected def stringPrefix = "ListBuffer" } diff --git a/library/src/scala/collection/mutable/ListMap.scala b/library/src/scala/collection/mutable/ListMap.scala index ce66f09b0233..b3fd650754a5 100644 --- a/library/src/scala/collection/mutable/ListMap.scala +++ b/library/src/scala/collection/mutable/ListMap.scala @@ -42,8 +42,8 @@ class ListMap[K, V] override def mapFactory: MapFactory[ListMap] = ListMap - private[this] var elems: List[(K, V)] = List() - private[this] var siz: Int = 0 + private var elems: List[(K, V)] = List() + private var siz: Int = 0 def get(key: K): Option[V] = elems find (_._1 == key) map (_._2) def iterator: Iterator[(K, V)] = elems.iterator @@ -68,7 +68,7 @@ class ListMap[K, V] final override def size: Int = siz override def knownSize: Int = size override def isEmpty: Boolean = size == 0 - override protected[this] def stringPrefix = "ListMap" + override protected def stringPrefix = "ListMap" } /** $factoryInfo diff --git a/library/src/scala/collection/mutable/LongMap.scala b/library/src/scala/collection/mutable/LongMap.scala index 171c9d44351a..0e54720363fc 100644 --- a/library/src/scala/collection/mutable/LongMap.scala +++ b/library/src/scala/collection/mutable/LongMap.scala @@ -70,18 +70,18 @@ final class LongMap[V] private[collection] (defaultEntry: Long -> V, initialBuff /** Creates a new `LongMap` with specified default values and initial buffer size. */ def this(defaultEntry: Long -> V, initialBufferSize: Int) = this(defaultEntry, initialBufferSize, initBlank = true) - private[this] var mask = 0 - private[this] var extraKeys: Int = 0 - @annotation.stableNull private[this] var zeroValue: AnyRef | Null = null - @annotation.stableNull private[this] var minValue: AnyRef | Null = null - private[this] var _size = 0 - private[this] var _vacant = 0 - private[this] var _keys: Array[Long] = _ - private[this] var _values: Array[AnyRef | Null] = _ + private var mask = 0 + private var extraKeys: Int = 0 + @annotation.stableNull private var zeroValue: AnyRef | Null = null + @annotation.stableNull private var minValue: AnyRef | Null = null + private var _size = 0 + private var _vacant = 0 + private var _keys: Array[Long] = compiletime.uninitialized + private var _values: Array[AnyRef | Null] = compiletime.uninitialized if (initBlank) defaultInitialize(initialBufferSize) - private[this] def defaultInitialize(n: Int) = { + private def defaultInitialize(n: Int) = { mask = if (n<0) 0x7 else (((1 << (32 - java.lang.Integer.numberOfLeadingZeros(n-1))) - 1) & 0x3FFFFFFF) | 0x7 @@ -384,19 +384,19 @@ final class LongMap[V] private[collection] (defaultEntry: Long -> V, initialBuff } def iterator: Iterator[(Long, V)] = new AbstractIterator[(Long, V)] { - private[this] val kz = _keys - private[this] val vz = _values + private val kz = _keys + private val vz = _values - private[this] var nextPair: (Long, V) | Null = + private var nextPair: (Long, V) | Null = if (extraKeys==0) null else if ((extraKeys&1)==1) (0L, zeroValue.asInstanceOf[V]) else (Long.MinValue, minValue.asInstanceOf[V]) - private[this] var anotherPair: (Long, V) | Null = + private var anotherPair: (Long, V) | Null = if (extraKeys==3) (Long.MinValue, minValue.asInstanceOf[V]) else null - private[this] var index = 0 + private var index = 0 def hasNext: Boolean = nextPair != null || (index < kz.length && { var q = kz(index) @@ -583,9 +583,9 @@ final class LongMap[V] private[collection] (defaultEntry: Long -> V, initialBuff def collect[V2](pf: PartialFunction[(Long, V), (Long, V2)]): LongMap[V2] = strictOptimizedCollect(LongMap.newBuilder[V2], pf) - protected[this] def writeReplace(): AnyRef = new DefaultSerializationProxy(LongMap.toFactory[V](LongMap), this) + protected def writeReplace(): AnyRef = new DefaultSerializationProxy(LongMap.toFactory[V](LongMap), this) - override protected[this] def className = "LongMap" + override protected def className = "LongMap" } object LongMap { @@ -671,7 +671,7 @@ object LongMap { implicit def toFactory[V](dummy: LongMap.type): Factory[(Long, V), LongMap[V]] = ToFactory.asInstanceOf[Factory[(Long, V), LongMap[V]]] @SerialVersionUID(3L) - private[this] object ToFactory extends Factory[(Long, AnyRef), LongMap[AnyRef]] with Serializable { + private object ToFactory extends Factory[(Long, AnyRef), LongMap[AnyRef]], Serializable { def fromSpecific(it: IterableOnce[(Long, AnyRef)]^): LongMap[AnyRef] = LongMap.from[AnyRef](it) def newBuilder: Builder[(Long, AnyRef), LongMap[AnyRef]] = LongMap.newBuilder[AnyRef] } @@ -683,7 +683,7 @@ object LongMap { } implicit def iterableFactory[V]: Factory[(Long, V), LongMap[V]] = toFactory(this) - implicit def buildFromLongMap[V]: BuildFrom[LongMap[_], (Long, V), LongMap[V]] = toBuildFrom(this) + implicit def buildFromLongMap[V]: BuildFrom[LongMap[?], (Long, V), LongMap[V]] = toBuildFrom(this) private def repackMask(mask: Int, _size: Int, _vacant: Int): Int = { var m = mask diff --git a/library/src/scala/collection/mutable/Map.scala b/library/src/scala/collection/mutable/Map.scala index 9e87fb25e88f..5fbeef3f2391 100644 --- a/library/src/scala/collection/mutable/Map.scala +++ b/library/src/scala/collection/mutable/Map.scala @@ -66,7 +66,7 @@ trait Map[K, V] * @define coll mutable map * @define Coll `mutable.Map` */ -transparent trait MapOps[K, V, +CC[X, Y] <: MapOps[X, Y, CC, _], +C <: MapOps[K, V, CC, C]] +transparent trait MapOps[K, V, +CC[X, Y] <: MapOps[X, Y, CC, ?], +C <: MapOps[K, V, CC, C]] extends IterableOps[(K, V), Iterable, C] with collection.MapOps[K, V, CC, C] with Cloneable[C] diff --git a/library/src/scala/collection/mutable/MutationTracker.scala b/library/src/scala/collection/mutable/MutationTracker.scala index ddd3a912a840..0443a9e6645f 100644 --- a/library/src/scala/collection/mutable/MutationTracker.scala +++ b/library/src/scala/collection/mutable/MutationTracker.scala @@ -69,7 +69,7 @@ private object MutationTracker { * @tparam A the type of the iterator's elements */ final class CheckedIterator[A](underlying: Iterator[A], mutationCount: => Int) extends AbstractIterator[A] { - private[this] val expectedCount = mutationCount + private val expectedCount = mutationCount def hasNext: Boolean = { checkMutationsForIteration(expectedCount, mutationCount) diff --git a/library/src/scala/collection/mutable/OpenHashMap.scala b/library/src/scala/collection/mutable/OpenHashMap.scala index 66a82fe50704..1f3a23da4447 100644 --- a/library/src/scala/collection/mutable/OpenHashMap.scala +++ b/library/src/scala/collection/mutable/OpenHashMap.scala @@ -79,26 +79,26 @@ class OpenHashMap[Key, Value](initialSize : Int) override def mapFactory: MapFactory[OpenHashMap] = OpenHashMap - private[this] val actualInitialSize = OpenHashMap.nextPositivePowerOfTwo(initialSize) + private val actualInitialSize = OpenHashMap.nextPositivePowerOfTwo(initialSize) - private[this] var mask = actualInitialSize - 1 + private var mask = actualInitialSize - 1 /** The hash table. * * The table's entries are initialized to `null`, indication of an empty slot. * A slot is either deleted or occupied if and only if the entry is non-`null`. */ - private[this] var table = new Array[Entry](actualInitialSize) + private var table = new Array[Entry](actualInitialSize) - private[this] var _size = 0 - private[this] var deleted = 0 + private var _size = 0 + private var deleted = 0 // Used for tracking inserts so that iterators can determine if concurrent modification has occurred. - private[this] var modCount = 0 + private var modCount = 0 override def size = _size override def knownSize: Int = size - private[this] def size_=(s : Int): Unit = _size = s + private def size_=(s : Int): Unit = _size = s override def isEmpty: Boolean = _size == 0 /** Returns a mangled hash code of the provided key. */ protected def hashOf(key: Key) = { @@ -110,7 +110,7 @@ class OpenHashMap[Key, Value](initialSize : Int) /** Increase the size of the table. * Copy only the occupied slots, effectively eliminating the deleted slots. */ - private[this] def growTable() = { + private def growTable() = { val oldSize = mask + 1 val newSize = 4 * oldSize val oldTable = table @@ -127,7 +127,7 @@ class OpenHashMap[Key, Value](initialSize : Int) * * @param hash hash value for `key` */ - private[this] def findIndex(key: Key, hash: Int): Int = { + private def findIndex(key: Key, hash: Int): Int = { var index = hash & mask var j = 0 @@ -187,7 +187,7 @@ class OpenHashMap[Key, Value](initialSize : Int) /** Delete the hash table slot contained in the given entry. */ @`inline` - private[this] def deleteSlot(entry: Entry) = { + private def deleteSlot(entry: Entry) = { entry.key = null.asInstanceOf[Key] entry.hash = 0 entry.value = None @@ -240,10 +240,10 @@ class OpenHashMap[Key, Value](initialSize : Int) } private abstract class OpenHashMapIterator[A] extends AbstractIterator[A] { - private[this] var index = 0 - private[this] val initialModCount = modCount + private var index = 0 + private val initialModCount = modCount - private[this] def advance(): Unit = { + private def advance(): Unit = { if (initialModCount != modCount) throw new ConcurrentModificationException while((index <= mask) && (table(index) == null || table(index).value == None)) index+=1 } @@ -290,7 +290,7 @@ class OpenHashMap[Key, Value](initialSize : Int) ) } - private[this] def foreachUndeletedEntry(f : Entry => Unit): Unit = { + private def foreachUndeletedEntry(f : Entry => Unit): Unit = { table.foreach(entry => if (entry != null && entry.value != None) f(entry)) } @@ -304,5 +304,5 @@ class OpenHashMap[Key, Value](initialSize : Int) this } - override protected[this] def stringPrefix = "OpenHashMap" + override protected def stringPrefix = "OpenHashMap" } diff --git a/library/src/scala/collection/mutable/PriorityQueue.scala b/library/src/scala/collection/mutable/PriorityQueue.scala index 2c1e1671b215..433c4dc7a62d 100644 --- a/library/src/scala/collection/mutable/PriorityQueue.scala +++ b/library/src/scala/collection/mutable/PriorityQueue.scala @@ -311,7 +311,7 @@ sealed class PriorityQueue[A](implicit val ord: Ordering[A]) * @return the reversed priority queue. */ def reverse: PriorityQueue[A] = { - val revq = new PriorityQueue[A]()(ord.reverse) + val revq = new PriorityQueue[A]()(using ord.reverse) // copy the existing data into the new array backwards // this won't put it exactly into the correct order, // but will require less fixing than copying it in @@ -335,7 +335,7 @@ sealed class PriorityQueue[A](implicit val ord: Ordering[A]) * @return an iterator over all elements sorted in descending order. */ def reverseIterator: Iterator[A] = new AbstractIterator[A] { - private[this] var i = resarr.p_size0 - 1 + private var i = resarr.p_size0 - 1 def hasNext: Boolean = i >= 1 def next(): A = { val n = resarr.p_array(i) @@ -388,9 +388,9 @@ sealed class PriorityQueue[A](implicit val ord: Ordering[A]) @deprecated("Use `PriorityQueue` instead", "2.13.0") def orderedCompanion: PriorityQueue.type = PriorityQueue - protected[this] def writeReplace(): AnyRef = new DefaultSerializationProxy(PriorityQueue.evidenceIterableFactory[A], this) + protected def writeReplace(): AnyRef = new DefaultSerializationProxy(PriorityQueue.evidenceIterableFactory[A], this) - override protected[this] def className = "PriorityQueue" + override protected def className = "PriorityQueue" } diff --git a/library/src/scala/collection/mutable/Queue.scala b/library/src/scala/collection/mutable/Queue.scala index a4b087e068c8..4a8e5c60b9f8 100644 --- a/library/src/scala/collection/mutable/Queue.scala +++ b/library/src/scala/collection/mutable/Queue.scala @@ -44,7 +44,7 @@ class Queue[A] protected (array: Array[AnyRef | Null], start: Int, end: Int) override def iterableFactory: SeqFactory[Queue] = Queue @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix = "Queue" + override protected def stringPrefix = "Queue" /** * Add elements to the end of this queue diff --git a/library/src/scala/collection/mutable/RedBlackTree.scala b/library/src/scala/collection/mutable/RedBlackTree.scala index b8347b5984c7..9fdd27ebb00c 100644 --- a/library/src/scala/collection/mutable/RedBlackTree.scala +++ b/library/src/scala/collection/mutable/RedBlackTree.scala @@ -67,15 +67,15 @@ private[collection] object RedBlackTree { // ---- getters ---- - def isRed(node: Node[_, _] | Null) = (node ne null) && node.red - def isBlack(node: Node[_, _] | Null) = (node eq null) || !node.red + def isRed(node: Node[?, ?] | Null) = (node ne null) && node.red + def isBlack(node: Node[?, ?] | Null) = (node eq null) || !node.red // ---- size ---- - def size(node: Node[_, _] | Null): Int = if (node eq null) 0 else 1 + size(node.left) + size(node.right) - def size(tree: Tree[_, _]): Int = tree.size - def isEmpty(tree: Tree[_, _]) = tree.root eq null - def clear(tree: Tree[_, _]): Unit = { tree.root = null; tree.size = 0 } + def size(node: Node[?, ?] | Null): Int = if (node eq null) 0 else 1 + size(node.left) + size(node.right) + def size(tree: Tree[?, ?]): Int = tree.size + def isEmpty(tree: Tree[?, ?]) = tree.root eq null + def clear(tree: Tree[?, ?]): Unit = { tree.root = null; tree.size = 0 } // ---- search ---- @@ -84,7 +84,7 @@ private[collection] object RedBlackTree { case node => Some(node.value) } - @tailrec private[this] def getNode[A, B](node: Node[A, B] | Null, key: A)(implicit ord: Ordering[A]): Node[A, B] | Null = + @tailrec private def getNode[A, B](node: Node[A, B] | Null, key: A)(implicit ord: Ordering[A]): Node[A, B] | Null = if (node eq null) null else { val cmp = ord.compare(key, node.key) @@ -93,14 +93,14 @@ private[collection] object RedBlackTree { else node } - def contains[A: Ordering](tree: Tree[A, _], key: A): Boolean = getNode(tree.root, key) ne null + def contains[A: Ordering](tree: Tree[A, ?], key: A): Boolean = getNode(tree.root, key) ne null def min[A, B](tree: Tree[A, B]): Option[(A, B)] = minNode(tree.root) match { case null => None case node => Some((node.key, node.value)) } - def minKey[A](tree: Tree[A, _]): Option[A] = minNode(tree.root) match { + def minKey[A](tree: Tree[A, ?]): Option[A] = minNode(tree.root) match { case null => None case node => Some(node.key) } @@ -116,7 +116,7 @@ private[collection] object RedBlackTree { case node => Some((node.key, node.value)) } - def maxKey[A](tree: Tree[A, _]): Option[A] = maxNode(tree.root) match { + def maxKey[A](tree: Tree[A, ?]): Option[A] = maxNode(tree.root) match { case null => None case node => Some(node.key) } @@ -137,13 +137,13 @@ private[collection] object RedBlackTree { case node => Some((node.key, node.value)) } - def minKeyAfter[A](tree: Tree[A, _], key: A)(implicit ord: Ordering[A]): Option[A] = + def minKeyAfter[A](tree: Tree[A, ?], key: A)(implicit ord: Ordering[A]): Option[A] = minNodeAfter(tree.root, key) match { case null => None case node => Some(node.key) } - private[this] def minNodeAfter[A, B](node: Node[A, B] | Null, key: A)(implicit ord: Ordering[A]): Node[A, B] | Null = { + private def minNodeAfter[A, B](node: Node[A, B] | Null, key: A)(implicit ord: Ordering[A]): Node[A, B] | Null = { if (node eq null) null else { // We know x is not null initially, so y will only be null before the first iteration of the loop. @@ -168,13 +168,13 @@ private[collection] object RedBlackTree { case node => Some((node.key, node.value)) } - def maxKeyBefore[A](tree: Tree[A, _], key: A)(implicit ord: Ordering[A]): Option[A] = + def maxKeyBefore[A](tree: Tree[A, ?], key: A)(implicit ord: Ordering[A]): Option[A] = maxNodeBefore(tree.root, key) match { case null => None case node => Some(node.key) } - private[this] def maxNodeBefore[A, B](node: Node[A, B] | Null, key: A)(implicit ord: Ordering[A]): Node[A, B] | Null = { + private def maxNodeBefore[A, B](node: Node[A, B] | Null, key: A)(implicit ord: Ordering[A]): Node[A, B] | Null = { if (node eq null) null else { // We know x is not null initially, so y will only be null before the first iteration of the loop. @@ -215,7 +215,7 @@ private[collection] object RedBlackTree { } } - private[this] def fixAfterInsert[A, B](tree: Tree[A, B], node: Node[A, B]): Unit = { + private def fixAfterInsert[A, B](tree: Tree[A, B], node: Node[A, B]): Unit = { var z = node while (isRed(z.parent)) { if (z.parent eq z.parent.nn.parent.nn.left) { @@ -298,7 +298,7 @@ private[collection] object RedBlackTree { } } - private[this] def fixAfterDelete[A, B](tree: Tree[A, B], node: Node[A, B] | Null, parent: Node[A, B] | Null): Unit = { + private def fixAfterDelete[A, B](tree: Tree[A, B], node: Node[A, B] | Null, parent: Node[A, B] | Null): Unit = { var x = node var xParent = parent while ((x ne tree.root) && isBlack(x)) { @@ -366,7 +366,7 @@ private[collection] object RedBlackTree { * Returns the node that follows `node` in an in-order tree traversal. If `node` has the maximum key (and is, * therefore, the last node), this method returns `null`. */ - private[this] def successor[A, B](node: Node[A, B]): Node[A, B] | Null = { + private def successor[A, B](node: Node[A, B]): Node[A, B] | Null = { if (node.right ne null) minNodeNonNull(node.right) else { var x = node @@ -383,7 +383,7 @@ private[collection] object RedBlackTree { * Returns the node that precedes `node` in an in-order tree traversal. If `node` has the minimum key (and is, * therefore, the first node), this method returns `null`. */ - private[this] def predecessor[A, B](node: Node[A, B]): Node[A, B] | Null = { + private def predecessor[A, B](node: Node[A, B]): Node[A, B] | Null = { if (node.left ne null) maxNodeNonNull(node.left) else { var x = node @@ -396,7 +396,7 @@ private[collection] object RedBlackTree { } } - private[this] def rotateLeft[A, B](tree: Tree[A, B], x: Node[A, B]): Unit = if (x ne null) { + private def rotateLeft[A, B](tree: Tree[A, B], x: Node[A, B]): Unit = if (x ne null) { // assert(x.right ne null) val y = x.right.nn x.right = y.left @@ -412,7 +412,7 @@ private[collection] object RedBlackTree { x.parent = y } - private[this] def rotateRight[A, B](tree: Tree[A, B], x: Node[A, B]): Unit = if (x ne null) { + private def rotateRight[A, B](tree: Tree[A, B], x: Node[A, B]): Unit = if (x ne null) { // assert(x.left ne null) val y = x.left.nn x.left = y.right @@ -432,7 +432,7 @@ private[collection] object RedBlackTree { * Transplant the node `from` to the place of node `to`. This is done by setting `from` as a child of `to`'s previous * parent and setting `from`'s parent to the `to`'s previous parent. The children of `from` are left unchanged. */ - private[this] def transplant[A, B](tree: Tree[A, B], to: Node[A, B], from: Node[A, B] | Null): Unit = { + private def transplant[A, B](tree: Tree[A, B], to: Node[A, B], from: Node[A, B] | Null): Unit = { if (to.parent eq null) tree.root = from else if (to eq to.parent.nn.left) to.parent.left = from else to.parent.right = from @@ -444,17 +444,17 @@ private[collection] object RedBlackTree { def foreach[A, B, U](tree: Tree[A, B], f: ((A, B)) => U): Unit = foreachNode(tree.root, f) - private[this] def foreachNode[A, B, U](node: Node[A, B] | Null, f: ((A, B)) => U): Unit = + private def foreachNode[A, B, U](node: Node[A, B] | Null, f: ((A, B)) => U): Unit = if (node ne null) foreachNodeNonNull(node, f) - private[this] def foreachNodeNonNull[A, B, U](node: Node[A, B], f: ((A, B)) => U): Unit = { + private def foreachNodeNonNull[A, B, U](node: Node[A, B], f: ((A, B)) => U): Unit = { if (node.left ne null) foreachNodeNonNull(node.left, f) f((node.key, node.value)) if (node.right ne null) foreachNodeNonNull(node.right, f) } - def foreachKey[A, U](tree: Tree[A, _], f: A => U): Unit = { - def g(node: Node[A, _]): Unit = { + def foreachKey[A, U](tree: Tree[A, ?], f: A => U): Unit = { + def g(node: Node[A, ?]): Unit = { val l = node.left if(l ne null) g(l) f(node.key) @@ -479,10 +479,10 @@ private[collection] object RedBlackTree { def transform[A, B](tree: Tree[A, B], f: (A, B) => B): Unit = transformNode(tree.root, f) - private[this] def transformNode[A, B, U](node: Node[A, B] | Null, f: (A, B) => B): Unit = + private def transformNode[A, B, U](node: Node[A, B] | Null, f: (A, B) => B): Unit = if (node ne null) transformNodeNonNull(node, f) - private[this] def transformNodeNonNull[A, B, U](node: Node[A, B], f: (A, B) => B): Unit = { + private def transformNodeNonNull[A, B, U](node: Node[A, B], f: (A, B) => B): Unit = { if (node.left ne null) transformNodeNonNull(node.left, f) node.value = f(node.key, node.value) if (node.right ne null) transformNodeNonNull(node.right, f) @@ -491,13 +491,13 @@ private[collection] object RedBlackTree { def iterator[A: Ordering, B](tree: Tree[A, B], start: Option[A] = None, end: Option[A] = None): Iterator[(A, B)] = new EntriesIterator(tree, start, end) - def keysIterator[A: Ordering](tree: Tree[A, _], start: Option[A] = None, end: Option[A] = None): Iterator[A] = + def keysIterator[A: Ordering](tree: Tree[A, ?], start: Option[A] = None, end: Option[A] = None): Iterator[A] = new KeysIterator(tree, start, end) def valuesIterator[A: Ordering, B](tree: Tree[A, B], start: Option[A] = None, end: Option[A] = None): Iterator[B] = new ValuesIterator(tree, start, end) - private[this] abstract class TreeIterator[A, B, R](tree: Tree[A, B], start: Option[A], end: Option[A]) + private abstract class TreeIterator[A, B, R](tree: Tree[A, B], start: Option[A], end: Option[A]) (implicit ord: Ordering[A]) extends AbstractIterator[R] { protected def nextResult(node: Node[A, B]): R @@ -513,30 +513,30 @@ private[collection] object RedBlackTree { nextResult(node) } - private[this] var nextNode: Node[A, B] | Null = start match { + private var nextNode: Node[A, B] | Null = start match { case None => minNode(tree.root) case Some(from) => minNodeAfter(tree.root, from) } - private[this] def setNullIfAfterEnd(): Unit = + private def setNullIfAfterEnd(): Unit = if (end.isDefined && (nextNode ne null) && ord.compare(nextNode.nn.key, end.get) >= 0) nextNode = null setNullIfAfterEnd() } - private[this] final class EntriesIterator[A: Ordering, B](tree: Tree[A, B], start: Option[A], end: Option[A]) + private final class EntriesIterator[A: Ordering, B](tree: Tree[A, B], start: Option[A], end: Option[A]) extends TreeIterator[A, B, (A, B)](tree, start, end) { def nextResult(node: Node[A, B]) = (node.key, node.value) } - private[this] final class KeysIterator[A: Ordering, B](tree: Tree[A, B], start: Option[A], end: Option[A]) + private final class KeysIterator[A: Ordering, B](tree: Tree[A, B], start: Option[A], end: Option[A]) extends TreeIterator[A, B, A](tree, start, end) { def nextResult(node: Node[A, B]) = node.key } - private[this] final class ValuesIterator[A: Ordering, B](tree: Tree[A, B], start: Option[A], end: Option[A]) + private final class ValuesIterator[A: Ordering, B](tree: Tree[A, B], start: Option[A], end: Option[A]) extends TreeIterator[A, B, B](tree, start, end) { def nextResult(node: Node[A, B]) = node.value @@ -557,7 +557,7 @@ private[collection] object RedBlackTree { /** * Returns true if all non-null nodes have their `parent` reference correct. */ - private[this] def hasProperParentRefs[A, B](tree: Tree[A, B]): Boolean = { + private def hasProperParentRefs[A, B](tree: Tree[A, B]): Boolean = { def hasProperParentRefs(node: Node[A, B] | Null): Boolean = { if (node eq null) true @@ -575,7 +575,7 @@ private[collection] object RedBlackTree { /** * Returns true if this node follows the properties of a binary search tree. */ - private[this] def isValidBST[A, B](node: Node[A, B] | Null)(implicit ord: Ordering[A]): Boolean = { + private def isValidBST[A, B](node: Node[A, B] | Null)(implicit ord: Ordering[A]): Boolean = { if (node eq null) true else { if ((node.left ne null) && (ord.compare(node.key, node.left.key) <= 0) || @@ -588,7 +588,7 @@ private[collection] object RedBlackTree { * Returns true if the tree has all the red-black tree properties: if the root node is black, if all children of red * nodes are black and if the path from any node to any of its null children has the same number of black nodes. */ - private[this] def isValidRedBlackTree[A, B](tree: Tree[A, B]): Boolean = { + private def isValidRedBlackTree[A, B](tree: Tree[A, B]): Boolean = { def noRedAfterRed(node: Node[A, B] | Null): Boolean = { if (node eq null) true diff --git a/library/src/scala/collection/mutable/SortedMap.scala b/library/src/scala/collection/mutable/SortedMap.scala index c16a01384785..5870e010cefd 100644 --- a/library/src/scala/collection/mutable/SortedMap.scala +++ b/library/src/scala/collection/mutable/SortedMap.scala @@ -53,7 +53,7 @@ trait SortedMap[K, V] override def withDefaultValue(d: V): SortedMap[K, V] = new SortedMap.WithDefault[K, V](this, _ => d) } -transparent trait SortedMapOps[K, V, +CC[X, Y] <: Map[X, Y] with SortedMapOps[X, Y, CC, _], +C <: SortedMapOps[K, V, CC, C]] +transparent trait SortedMapOps[K, V, +CC[X, Y] <: Map[X, Y] & SortedMapOps[X, Y, CC, ?], +C <: SortedMapOps[K, V, CC, C]] extends collection.SortedMapOps[K, V, CC, C] with MapOps[K, V, Map, C] { diff --git a/library/src/scala/collection/mutable/Stack.scala b/library/src/scala/collection/mutable/Stack.scala index 26cda88ecd4f..e08671add9c2 100644 --- a/library/src/scala/collection/mutable/Stack.scala +++ b/library/src/scala/collection/mutable/Stack.scala @@ -50,7 +50,7 @@ class Stack[A] protected (array: Array[AnyRef | Null], start: Int, end: Int) override def iterableFactory: SeqFactory[Stack] = Stack @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix = "Stack" + override protected def stringPrefix = "Stack" /** * Add elements to the top of this stack diff --git a/library/src/scala/collection/mutable/StringBuilder.scala b/library/src/scala/collection/mutable/StringBuilder.scala index 91baa747f219..c283066eb64f 100644 --- a/library/src/scala/collection/mutable/StringBuilder.scala +++ b/library/src/scala/collection/mutable/StringBuilder.scala @@ -78,7 +78,7 @@ final class StringBuilder(val underlying: java.lang.StringBuilder) extends Abstr * and with additional character capacity `initCapacity`. */ def this(initCapacity: Int, initValue: String) = - this(new java.lang.StringBuilder(initValue.length + initCapacity) append initValue) + this(new java.lang.StringBuilder(initValue.length + initCapacity).append(initValue)) // Methods required to make this an IndexedSeq: def apply(i: Int): Char = underlying.charAt(i) @@ -131,7 +131,7 @@ final class StringBuilder(val underlying: java.lang.StringBuilder) extends Abstr // append* methods delegate to the underlying java.lang.StringBuilder: def appendAll(xs: String): this.type = { - underlying append xs + underlying.append(xs) this } @@ -142,7 +142,7 @@ final class StringBuilder(val underlying: java.lang.StringBuilder) extends Abstr * @return this StringBuilder. */ def append(x: Any): this.type = { - underlying append String.valueOf(x) + underlying.append(String.valueOf(x)) this } @@ -152,7 +152,7 @@ final class StringBuilder(val underlying: java.lang.StringBuilder) extends Abstr * @return this StringBuilder. */ def append(s: String): this.type = { - underlying append s + underlying.append(s) this } @@ -177,7 +177,7 @@ final class StringBuilder(val underlying: java.lang.StringBuilder) extends Abstr * @return */ def append(s: StringBuilder): this.type = { - underlying append s.underlying + underlying.append(s.underlying) this } @@ -188,16 +188,16 @@ final class StringBuilder(val underlying: java.lang.StringBuilder) extends Abstr */ def appendAll(xs: IterableOnce[Char]^): this.type = { xs match { - case x: WrappedString => underlying append x.unwrap - case x: ArraySeq.ofChar => underlying append x.array - case x: StringBuilder => underlying append x.underlying + case x: WrappedString => underlying.append(x.unwrap) + case x: ArraySeq.ofChar => underlying.append(x.array) + case x: StringBuilder => underlying.append(x.underlying) case _ => val ks = xs.knownSize if (ks != 0) { val b = underlying if (ks > 0) b.ensureCapacity(b.length + ks) val it = xs.iterator - while (it.hasNext) { b append it.next() } + while (it.hasNext) { b.append(it.next()) } } } this @@ -209,7 +209,7 @@ final class StringBuilder(val underlying: java.lang.StringBuilder) extends Abstr * @return a reference to this object. */ def appendAll(xs: Array[Char]): this.type = { - underlying append xs + underlying.append(xs) this } @@ -232,14 +232,14 @@ final class StringBuilder(val underlying: java.lang.StringBuilder) extends Abstr * @param x a primitive value * @return This StringBuilder. */ - def append(x: Boolean): this.type = { underlying append x ; this } + def append(x: Boolean): this.type = { underlying.append(x) ; this } def append(x: Byte): this.type = append(x.toInt) def append(x: Short): this.type = append(x.toInt) - def append(x: Int): this.type = { underlying append x ; this } - def append(x: Long): this.type = { underlying append x ; this } - def append(x: Float): this.type = { underlying append x ; this } - def append(x: Double): this.type = { underlying append x ; this } - def append(x: Char): this.type = { underlying append x ; this } + def append(x: Int): this.type = { underlying.append(x) ; this } + def append(x: Long): this.type = { underlying.append (x) ; this } + def append(x: Float): this.type = { underlying.append (x) ; this } + def append(x: Double): this.type = { underlying.append(x) ; this } + def append(x: Char): this.type = { underlying.append(x) ; this } /** Remove a subsequence of Chars from this sequence, starting at the * given start index (inclusive) and extending to the end index (exclusive) diff --git a/library/src/scala/collection/mutable/TreeMap.scala b/library/src/scala/collection/mutable/TreeMap.scala index 04bd71a424d6..acafb57c2c22 100644 --- a/library/src/scala/collection/mutable/TreeMap.scala +++ b/library/src/scala/collection/mutable/TreeMap.scala @@ -47,7 +47,7 @@ sealed class TreeMap[K, V] private (tree: RB.Tree[K, V])(implicit val ordering: * @param ord the implicit ordering used to compare objects of type `K`. * @return an empty `TreeMap`. */ - def this()(implicit ord: Ordering[K]) = this(RB.Tree.empty)(ord) + def this()(implicit ord: Ordering[K]) = this(RB.Tree.empty)(using ord) def iterator: Iterator[(K, V)] = { if (isEmpty) Iterator.empty @@ -79,14 +79,14 @@ sealed class TreeMap[K, V] private (tree: RB.Tree[K, V])(implicit val ordering: else RB.valuesIterator(tree, Some(start)) } - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[(K, V), S]): S with EfficientSplit = + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[(K, V), S]): S & EfficientSplit = shape.parUnbox( scala.collection.convert.impl.AnyBinaryTreeStepper.from[(K, V), RB.Node[K, V]]( size, tree.root, _.left, _.right, x => (x.key, x.value) ) ) - override def keyStepper[S <: Stepper[_]](implicit shape: StepperShape[K, S]): S with EfficientSplit = { + override def keyStepper[S <: Stepper[?]](implicit shape: StepperShape[K, S]): S & EfficientSplit = { import scala.collection.convert.impl._ type T = RB.Node[K, V] val s = shape.shape match { @@ -95,10 +95,10 @@ sealed class TreeMap[K, V] private (tree: RB.Tree[K, V])(implicit val ordering: case StepperShape.DoubleShape => DoubleBinaryTreeStepper.from[T](size, tree.root, _.left, _.right, _.key.asInstanceOf[Double]) case _ => shape.parUnbox(AnyBinaryTreeStepper.from[K, T](size, tree.root, _.left, _.right, _.key)) } - s.asInstanceOf[S with EfficientSplit] + s.asInstanceOf[S & EfficientSplit] } - override def valueStepper[S <: Stepper[_]](implicit shape: StepperShape[V, S]): S with EfficientSplit = { + override def valueStepper[S <: Stepper[?]](implicit shape: StepperShape[V, S]): S & EfficientSplit = { import scala.collection.convert.impl._ type T = RB.Node[K, V] val s = shape.shape match { @@ -107,7 +107,7 @@ sealed class TreeMap[K, V] private (tree: RB.Tree[K, V])(implicit val ordering: case StepperShape.DoubleShape => DoubleBinaryTreeStepper.from[T] (size, tree.root, _.left, _.right, _.value.asInstanceOf[Double]) case _ => shape.parUnbox(AnyBinaryTreeStepper.from[V, T] (size, tree.root, _.left, _.right, _.value)) } - s.asInstanceOf[S with EfficientSplit] + s.asInstanceOf[S & EfficientSplit] } def addOne(elem: (K, V)): this.type = { RB.insert(tree, elem._1, elem._2); this } @@ -151,7 +151,7 @@ sealed class TreeMap[K, V] private (tree: RB.Tree[K, V])(implicit val ordering: override def maxBefore(key: K): Option[(K, V)] = RB.maxBefore(tree, key) - override protected[this] def className: String = "TreeMap" + override protected def className: String = "TreeMap" /** @@ -167,12 +167,12 @@ sealed class TreeMap[K, V] private (tree: RB.Tree[K, V])(implicit val ordering: * @param until the upper bound (exclusive) of this projection wrapped in a `Some`, or `None` if there is no upper * bound. */ - private[this] final class TreeMapProjection(from: Option[K], until: Option[K]) extends TreeMap[K, V](tree) { + private final class TreeMapProjection(from: Option[K], until: Option[K]) extends TreeMap[K, V](tree) { /** * Given a possible new lower bound, chooses and returns the most constraining one (the maximum). */ - private[this] def pickLowerBound(newFrom: Option[K]): Option[K] = (from, newFrom) match { + private def pickLowerBound(newFrom: Option[K]): Option[K] = (from, newFrom) match { case (Some(fr), Some(newFr)) => Some(ordering.max(fr, newFr)) case (None, _) => newFrom case _ => from @@ -181,7 +181,7 @@ sealed class TreeMap[K, V] private (tree: RB.Tree[K, V])(implicit val ordering: /** * Given a possible new upper bound, chooses and returns the most constraining one (the minimum). */ - private[this] def pickUpperBound(newUntil: Option[K]): Option[K] = (until, newUntil) match { + private def pickUpperBound(newUntil: Option[K]): Option[K] = (until, newUntil) match { case (Some(unt), Some(newUnt)) => Some(ordering.min(unt, newUnt)) case (None, _) => newUntil case _ => until @@ -190,7 +190,7 @@ sealed class TreeMap[K, V] private (tree: RB.Tree[K, V])(implicit val ordering: /** * Returns true if the argument is inside the view bounds (between `from` and `until`). */ - private[this] def isInsideViewBounds(key: K): Boolean = { + private def isInsideViewBounds(key: K): Boolean = { val afterFrom = from.isEmpty || ordering.compare(from.get, key) <= 0 val beforeUntil = until.isEmpty || ordering.compare(key, until.get) < 0 afterFrom && beforeUntil diff --git a/library/src/scala/collection/mutable/TreeSet.scala b/library/src/scala/collection/mutable/TreeSet.scala index f54423cbe12d..a593b2f55a0d 100644 --- a/library/src/scala/collection/mutable/TreeSet.scala +++ b/library/src/scala/collection/mutable/TreeSet.scala @@ -47,7 +47,7 @@ sealed class TreeSet[A] private (private val tree: RB.Tree[A, Null])(implicit va * @param ord the implicit ordering used to compare objects of type `A`. * @return an empty `TreeSet`. */ - def this()(implicit ord: Ordering[A]) = this(RB.Tree.empty)(ord) + def this()(implicit ord: Ordering[A]) = this(RB.Tree.empty)(using ord) override def sortedIterableFactory: SortedIterableFactory[TreeSet] = TreeSet @@ -55,7 +55,7 @@ sealed class TreeSet[A] private (private val tree: RB.Tree[A, Null])(implicit va def iteratorFrom(start: A): collection.Iterator[A] = RB.keysIterator(tree, Some(start)) - override def stepper[S <: Stepper[_]](implicit shape: StepperShape[A, S]): S with EfficientSplit = { + override def stepper[S <: Stepper[?]](implicit shape: StepperShape[A, S]): S & EfficientSplit = { import scala.collection.convert.impl._ type T = RB.Node[A, Null] val s = shape.shape match { @@ -64,7 +64,7 @@ sealed class TreeSet[A] private (private val tree: RB.Tree[A, Null])(implicit va case StepperShape.DoubleShape => DoubleBinaryTreeStepper.from[T](size, tree.root, _.left, _.right, _.key.asInstanceOf[Double]) case _ => shape.parUnbox(AnyBinaryTreeStepper.from[A, T](size, tree.root, _.left, _.right, _.key)) } - s.asInstanceOf[S with EfficientSplit] + s.asInstanceOf[S & EfficientSplit] } def addOne(elem: A): this.type = { @@ -85,7 +85,7 @@ sealed class TreeSet[A] private (private val tree: RB.Tree[A, Null])(implicit va def rangeImpl(from: Option[A], until: Option[A]): TreeSet[A] = new TreeSetProjection(from, until) - override protected[this] def className: String = "TreeSet" + override protected def className: String = "TreeSet" override def size: Int = RB.size(tree) override def knownSize: Int = size @@ -115,13 +115,13 @@ sealed class TreeSet[A] private (private val tree: RB.Tree[A, Null])(implicit va * @param until the upper bound (exclusive) of this projection wrapped in a `Some`, or `None` if there is no upper * bound. */ - private[this] final class TreeSetProjection(from: Option[A], until: Option[A]) extends TreeSet[A](tree) { + private final class TreeSetProjection(from: Option[A], until: Option[A]) extends TreeSet[A](tree) { self: TreeSetProjection^{} => /** * Given a possible new lower bound, chooses and returns the most constraining one (the maximum). */ - private[this] def pickLowerBound(newFrom: Option[A]): Option[A] = (from, newFrom) match { + private def pickLowerBound(newFrom: Option[A]): Option[A] = (from, newFrom) match { case (Some(fr), Some(newFr)) => Some(ordering.max(fr, newFr)) case (None, _) => newFrom case _ => from @@ -130,7 +130,7 @@ sealed class TreeSet[A] private (private val tree: RB.Tree[A, Null])(implicit va /** * Given a possible new upper bound, chooses and returns the most constraining one (the minimum). */ - private[this] def pickUpperBound(newUntil: Option[A]): Option[A] = (until, newUntil) match { + private def pickUpperBound(newUntil: Option[A]): Option[A] = (until, newUntil) match { case (Some(unt), Some(newUnt)) => Some(ordering.min(unt, newUnt)) case (None, _) => newUntil case _ => until @@ -139,7 +139,7 @@ sealed class TreeSet[A] private (private val tree: RB.Tree[A, Null])(implicit va /** * Returns true if the argument is inside the view bounds (between `from` and `until`). */ - private[this] def isInsideViewBounds(key: A): Boolean = { + private def isInsideViewBounds(key: A): Boolean = { val afterFrom = from.isEmpty || ordering.compare(from.get, key) <= 0 val beforeUntil = until.isEmpty || ordering.compare(key, until.get) < 0 afterFrom && beforeUntil @@ -213,7 +213,7 @@ object TreeSet extends SortedIterableFactory[TreeSet] { } def newBuilder[A](implicit ordering: Ordering[A]): Builder[A, TreeSet[A]] = new ReusableBuilder[A, TreeSet[A]] { - private[this] var tree: RB.Tree[A, Null] = RB.Tree.empty + private var tree: RB.Tree[A, Null] = RB.Tree.empty def addOne(elem: A): this.type = { RB.insert(tree, elem, null); this } def result(): TreeSet[A] = new TreeSet[A](tree) def clear(): Unit = { tree = RB.Tree.empty } diff --git a/library/src/scala/collection/mutable/UnrolledBuffer.scala b/library/src/scala/collection/mutable/UnrolledBuffer.scala index a3d34d4d06a3..bfc5582f5391 100644 --- a/library/src/scala/collection/mutable/UnrolledBuffer.scala +++ b/library/src/scala/collection/mutable/UnrolledBuffer.scala @@ -217,8 +217,8 @@ sealed class UnrolledBuffer[T](implicit val tag: ClassTag[T]) private def writeObject(out: java.io.ObjectOutputStream): Unit = { out.defaultWriteObject - out writeInt sz - for (elem <- this) out writeObject elem + out.writeInt(sz) + for (elem <- this) out.writeObject(elem) } private def readObject(in: java.io.ObjectInputStream): Unit = { @@ -238,7 +238,7 @@ sealed class UnrolledBuffer[T](implicit val tag: ClassTag[T]) override def clone(): UnrolledBuffer[T] = new UnrolledBuffer[T] ++= this - override protected[this] def className = "UnrolledBuffer" + override protected def className = "UnrolledBuffer" } @@ -444,7 +444,7 @@ object UnrolledBuffer extends StrictOptimizedClassTagSeqFactory[UnrolledBuffer] // This is used by scala.collection.parallel.mutable.UnrolledParArrayCombiner: // Todo -- revisit whether inheritance is the best way to achieve this functionality -private[collection] class DoublingUnrolledBuffer[T](implicit t: ClassTag[T]) extends UnrolledBuffer[T]()(t) { +private[collection] class DoublingUnrolledBuffer[T](implicit t: ClassTag[T]) extends UnrolledBuffer[T]()(using t) { override def calcNextLength(sz: Int) = if (sz < 10000) sz * 2 else sz override protected def newUnrolled = new UnrolledBuffer.Unrolled[T](0, new Array[T](4), null, this) } diff --git a/library/src/scala/collection/mutable/WeakHashMap.scala b/library/src/scala/collection/mutable/WeakHashMap.scala index 0f8a66f1c840..988b26609fee 100644 --- a/library/src/scala/collection/mutable/WeakHashMap.scala +++ b/library/src/scala/collection/mutable/WeakHashMap.scala @@ -41,7 +41,7 @@ class WeakHashMap[K, V] extends JMapWrapper[K, V](new java.util.WeakHashMap) override def empty = new WeakHashMap[K, V] override def mapFactory: MapFactory[WeakHashMap] = WeakHashMap @nowarn("""cat=deprecation&origin=scala\.collection\.Iterable\.stringPrefix""") - override protected[this] def stringPrefix = "WeakHashMap" + override protected def stringPrefix = "WeakHashMap" } /** $factoryInfo diff --git a/library/src/scala/collection/mutable/package.scala b/library/src/scala/collection/mutable/package.scala index 5013839d5587..1473a89e846d 100644 --- a/library/src/scala/collection/mutable/package.scala +++ b/library/src/scala/collection/mutable/package.scala @@ -30,7 +30,7 @@ package object mutable { val ArrayStack = Stack @deprecated("mutable.LinearSeq has been removed; use LinearSeq with mutable.Seq instead", "2.13.0") - type LinearSeq[X] = Seq[X] with scala.collection.LinearSeq[X] + type LinearSeq[X] = Seq[X] & scala.collection.LinearSeq[X] @deprecated("GrowingBuilder has been renamed to GrowableBuilder", "2.13.0") type GrowingBuilder[Elem, To <: Growable[Elem]] = GrowableBuilder[Elem, To] diff --git a/library/src/scala/collection/package.scala b/library/src/scala/collection/package.scala index f43e22b531a7..4e5887985d43 100644 --- a/library/src/scala/collection/package.scala +++ b/library/src/scala/collection/package.scala @@ -66,7 +66,7 @@ package object collection { /** Splits a sequence into head +: tail. * @return Some((head, tail)) if sequence is non-empty. None otherwise. */ - def unapply[A, CC[_] <: Seq[_], C <: SeqOps[A, CC, C]](t: (C with SeqOps[A, CC, C])^): Option[(A, C^{t})] = + def unapply[A, CC[_] <: Seq[?], C <: SeqOps[A, CC, C]](t: (C & SeqOps[A, CC, C])^): Option[(A, C^{t})] = if(t.isEmpty) None else Some(t.head -> t.tail) } @@ -76,7 +76,7 @@ package object collection { /** Splits a sequence into init :+ last. * @return Some((init, last)) if sequence is non-empty. None otherwise. */ - def unapply[A, CC[_] <: Seq[_], C <: SeqOps[A, CC, C]](t: (C with SeqOps[A, CC, C])^): Option[(C^{t}, A)] = + def unapply[A, CC[_] <: Seq[?], C <: SeqOps[A, CC, C]](t: (C & SeqOps[A, CC, C])^): Option[(C^{t}, A)] = if(t.isEmpty) None else Some(t.init -> t.last) } diff --git a/library/src/scala/compat/Platform.scala b/library/src/scala/compat/Platform.scala index b6140e34afba..a47beb322f6a 100644 --- a/library/src/scala/compat/Platform.scala +++ b/library/src/scala/compat/Platform.scala @@ -84,7 +84,7 @@ object Platform { */ @inline @deprecated("Use `java.lang.reflect.Array#newInstance` instead.", since = "2.13.0") - def createArray(elemClass: Class[_], length: Int): AnyRef = + def createArray(elemClass: Class[?], length: Int): AnyRef = java.lang.reflect.Array.newInstance(elemClass, length) /** Assigns the value of 0 to each element in the array. @@ -111,7 +111,7 @@ object Platform { */ @inline @deprecated("Use `java.lang.Class#forName` instead.", since = "2.13.0") - def getClassForName(name: String): Class[_] = java.lang.Class.forName(name) + def getClassForName(name: String): Class[?] = java.lang.Class.forName(name) /** The default line separator. * diff --git a/library/src/scala/concurrent/BatchingExecutor.scala b/library/src/scala/concurrent/BatchingExecutor.scala index b69dc86fd181..58a540e9977e 100644 --- a/library/src/scala/concurrent/BatchingExecutor.scala +++ b/library/src/scala/concurrent/BatchingExecutor.scala @@ -91,20 +91,20 @@ private[concurrent] object BatchingExecutorStatics { * */ private[concurrent] trait BatchingExecutor extends Executor { - private[this] final val _tasksLocal = new ThreadLocal[AnyRef]() + private final val _tasksLocal = new ThreadLocal[AnyRef]() /* * Batch implements a LIFO queue (stack) and is used as a trampolining Runnable. * In order to conserve allocations, the first element in the batch is stored "unboxed" in * the `first` field. Subsequent Runnables are stored in the array called `other`. */ - private[this] sealed abstract class AbstractBatch protected ( + private sealed abstract class AbstractBatch protected ( @annotation.stableNull protected final var first: Runnable | Null, protected final var other: Array[Runnable | Null], protected final var size: Int ) { - private[this] final def ensureCapacity(curSize: Int): Array[Runnable | Null] = { + private final def ensureCapacity(curSize: Int): Array[Runnable | Null] = { val curOther = this.other val curLen = curOther.length if (curSize <= curLen) curOther @@ -148,8 +148,8 @@ private[concurrent] trait BatchingExecutor extends Executor { } } - private[this] final class AsyncBatch private(_first: Runnable | Null, _other: Array[Runnable | Null], _size: Int) extends AbstractBatch(_first, _other, _size) with Runnable with BlockContext with (BlockContext => Throwable | Null) { - private[this] final var parentBlockContext: BlockContext = BatchingExecutorStatics.MissingParentBlockContext + private final class AsyncBatch private(_first: Runnable | Null, _other: Array[Runnable | Null], _size: Int) extends AbstractBatch(_first, _other, _size) with Runnable with BlockContext with (BlockContext => Throwable | Null) { + private final var parentBlockContext: BlockContext = BatchingExecutorStatics.MissingParentBlockContext final def this(runnable: Runnable) = this(runnable, BatchingExecutorStatics.emptyBatchArray, 1) @@ -179,7 +179,7 @@ private[concurrent] trait BatchingExecutor extends Executor { * Only attempt to resubmit when there are `Runnables` left to process. * Note that `cause` can be `null`. */ - private[this] final def resubmit(cause: Throwable | Null): Throwable | Null = + private final def resubmit(cause: Throwable | Null): Throwable | Null = if (this.size > 0) { try { submitForExecution(this); cause } catch { case inner: Throwable => @@ -191,7 +191,7 @@ private[concurrent] trait BatchingExecutor extends Executor { } } else cause // TODO: consider if NonFatals should simply be `reportFailure`:ed rather than rethrown - private[this] final def cloneAndClear(): AsyncBatch = { + private final def cloneAndClear(): AsyncBatch = { val newBatch = new AsyncBatch(this.first, this.other, this.size) this.first = null this.other = BatchingExecutorStatics.emptyBatchArray @@ -208,7 +208,7 @@ private[concurrent] trait BatchingExecutor extends Executor { } } - private[this] final class SyncBatch(runnable: Runnable) extends AbstractBatch(runnable, BatchingExecutorStatics.emptyBatchArray, 1) with Runnable { + private final class SyncBatch(runnable: Runnable) extends AbstractBatch(runnable, BatchingExecutorStatics.emptyBatchArray, 1) with Runnable { @tailrec override final def run(): Unit = { try runN(BatchingExecutorStatics.runLimit) catch { case ie: InterruptedException => diff --git a/library/src/scala/concurrent/BlockContext.scala b/library/src/scala/concurrent/BlockContext.scala index bec31c270038..f932256441ad 100644 --- a/library/src/scala/concurrent/BlockContext.scala +++ b/library/src/scala/concurrent/BlockContext.scala @@ -60,7 +60,7 @@ trait BlockContext { } object BlockContext { - private[this] object DefaultBlockContext extends BlockContext { + private object DefaultBlockContext extends BlockContext { override final def blockOn[T](thunk: => T)(implicit permission: CanAwait): T = thunk } @@ -70,9 +70,9 @@ object BlockContext { **/ final def defaultBlockContext: BlockContext = DefaultBlockContext - private[this] final val contextLocal = new ThreadLocal[BlockContext]() + private final val contextLocal = new ThreadLocal[BlockContext]() - private[this] final def prefer(candidate: BlockContext): BlockContext = + private final def prefer(candidate: BlockContext): BlockContext = if (candidate ne null) candidate else { val t = Thread.currentThread diff --git a/library/src/scala/concurrent/Channel.scala b/library/src/scala/concurrent/Channel.scala index ebb3b324ef5a..22305159ae9f 100644 --- a/library/src/scala/concurrent/Channel.scala +++ b/library/src/scala/concurrent/Channel.scala @@ -22,12 +22,12 @@ import scala.language.`2.13` @deprecated("Use `java.util.concurrent.LinkedTransferQueue` instead.", since = "2.13.0") class Channel[A] { private class LinkedList { - var elem: A = _ - var next: LinkedList = _ + var elem: A = compiletime.uninitialized + var next: LinkedList = compiletime.uninitialized } - private[this] var written = new LinkedList // FIFO queue, realized through - private[this] var lastWritten = written // aliasing of a linked list - private[this] var nreaders = 0 + private var written = new LinkedList // FIFO queue, realized through + private var lastWritten = written // aliasing of a linked list + private var nreaders = 0 /** Append a value to the FIFO queue to be read by `read`. * This operation is nonblocking and can be executed by any thread. diff --git a/library/src/scala/concurrent/DelayedLazyVal.scala b/library/src/scala/concurrent/DelayedLazyVal.scala index 0406e7c0d7f7..09839517f7f6 100644 --- a/library/src/scala/concurrent/DelayedLazyVal.scala +++ b/library/src/scala/concurrent/DelayedLazyVal.scala @@ -27,8 +27,8 @@ import scala.language.`2.13` */ @deprecated("`DelayedLazyVal` Will be removed in the future.", since = "2.13.0") class DelayedLazyVal[T](f: () => T, body: => Unit)(implicit exec: ExecutionContext){ - @volatile private[this] var _isDone = false - private[this] lazy val complete = f() + @volatile private var _isDone = false + private lazy val complete = f() /** Whether the computation is complete. * diff --git a/library/src/scala/concurrent/ExecutionContext.scala b/library/src/scala/concurrent/ExecutionContext.scala index 625a0c3cbeba..07cc5e978960 100644 --- a/library/src/scala/concurrent/ExecutionContext.scala +++ b/library/src/scala/concurrent/ExecutionContext.scala @@ -231,7 +231,7 @@ object ExecutionContext { final override def submitForExecution(runnable: Runnable): Unit = global.execute(runnable) final override def execute(runnable: Runnable): Unit = - if ((!runnable.isInstanceOf[impl.Promise.Transformation[_,_]] || runnable.asInstanceOf[impl.Promise.Transformation[_,_]].benefitsFromBatching) && runnable.isInstanceOf[Batchable]) + if ((!runnable.isInstanceOf[impl.Promise.Transformation[?, ?]] || runnable.asInstanceOf[impl.Promise.Transformation[?, ?]].benefitsFromBatching) && runnable.isInstanceOf[Batchable]) submitAsyncBatched(runnable) else submitForExecution(runnable) diff --git a/library/src/scala/concurrent/Future.scala b/library/src/scala/concurrent/Future.scala index 5ff7be76599c..7ca677721c28 100644 --- a/library/src/scala/concurrent/Future.scala +++ b/library/src/scala/concurrent/Future.scala @@ -165,7 +165,7 @@ trait Future[+T] extends Awaitable[T] { * @return a failed projection of this `Future`. * @group Transformations */ - def failed: Future[Throwable] = transform(Future.failedFun)(parasitic) + def failed: Future[Throwable] = transform(Future.failedFun)(using parasitic) /* Monadic operations */ @@ -271,7 +271,7 @@ trait Future[+T] extends Awaitable[T] { * @tparam S the type of the returned `Future` * @group Transformations */ - def flatten[S](implicit ev: T <:< Future[S]): Future[S] = flatMap(ev)(parasitic) + def flatten[S](implicit ev: T <:< Future[S]): Future[S] = flatMap(ev)(using parasitic) /** Creates a new future by filtering the value of the current future with a predicate. * @@ -305,7 +305,7 @@ trait Future[+T] extends Awaitable[T] { /** Used by for-comprehensions. * @group Transformations */ - final def withFilter(p: T => Boolean)(implicit executor: ExecutionContext): Future[T] = filter(p)(executor) + final def withFilter(p: T => Boolean)(implicit executor: ExecutionContext): Future[T] = filter(p)(using executor) /** Creates a new future by mapping the value of the current future, if the given partial function is defined at that value. * @@ -403,7 +403,7 @@ trait Future[+T] extends Awaitable[T] { * @group Transformations */ def zip[U](that: Future[U]): Future[(T, U)] = - zipWith(that)(Future.zipWithTuple2Fun)(parasitic) + zipWith(that)(Future.zipWithTuple2Fun)(using parasitic) /** Zips the values of `this` and `that` future using a function `f`, * and creates a new future holding the result. @@ -427,7 +427,7 @@ trait Future[+T] extends Awaitable[T] { // // TODO: remove this implementation and make Future#zipWith abstract // when we're next willing to make a binary incompatible change - flatMap(r1 => that.map(r2 => f(r1, r2)))(if (executor.isInstanceOf[BatchingExecutor]) executor else parasitic) + flatMap(r1 => that.map(r2 => f(r1, r2)))(using if (executor.isInstanceOf[BatchingExecutor]) executor else parasitic) } /** Creates a new future which holds the result of this future if it was completed successfully, or, if not, @@ -531,7 +531,7 @@ object Future { * Utilities, hoisted functions, etc. */ - private[concurrent] final val toBoxed = Map[Class[_], Class[_]]( + private[concurrent] final val toBoxed = Map[Class[?], Class[?]]( classOf[Boolean] -> classOf[java.lang.Boolean], classOf[Byte] -> classOf[java.lang.Byte], classOf[Char] -> classOf[java.lang.Character], @@ -543,7 +543,7 @@ object Future { classOf[Unit] -> classOf[scala.runtime.BoxedUnit] ) - private[this] final val _cachedId: AnyRef => AnyRef = Predef.identity _ + private final val _cachedId: AnyRef => AnyRef = Predef.identity private[concurrent] final def id[T]: T => T = _cachedId.asInstanceOf[T => T] @@ -553,13 +553,13 @@ object Future { private[concurrent] final val filterFailure = Failure[Nothing](new NoSuchElementException("Future.filter predicate is not satisfied") with NoStackTrace) - private[this] final val failedFailure = + private final val failedFailure = Failure[Nothing](new NoSuchElementException("Future.failed not completed with a throwable.") with NoStackTrace) private[concurrent] final val failedFailureFuture: Future[Nothing] = scala.concurrent.Future.fromTry(failedFailure) - private[this] final val _failedFun: Try[Any] => Try[Throwable] = + private final val _failedFun: Try[Any] => Try[Throwable] = v => if (v.isInstanceOf[Failure[Any]]) Success(v.asInstanceOf[Failure[Any]].exception) else failedFailure private[concurrent] final def failedFun[T]: Try[T] => Try[Throwable] = _failedFun.asInstanceOf[Try[T] => Try[Throwable]] @@ -569,10 +569,10 @@ object Future { private[concurrent] final val recoverWithFailed = (t: Throwable) => recoverWithFailedMarker - private[this] final val _zipWithTuple2: (Any, Any) => (Any, Any) = Tuple2.apply _ + private final val _zipWithTuple2: (Any, Any) => (Any, Any) = Tuple2.apply private[concurrent] final def zipWithTuple2Fun[T,U] = _zipWithTuple2.asInstanceOf[(T,U) => (T,U)] - private[this] final val _addToBuilderFun: (Builder[Any, Nothing], Any) => Builder[Any, Nothing] = (b: Builder[Any, Nothing], e: Any) => b += e + private final val _addToBuilderFun: (Builder[Any, Nothing], Any) => Builder[Any, Nothing] = (b: Builder[Any, Nothing], e: Any) => b += e private[concurrent] final def addToBuilderFun[A, M] = _addToBuilderFun.asInstanceOf[Function2[Builder[A, M], A, Builder[A, M]]] private[concurrent] def waitUndefinedError(): Nothing = @@ -723,7 +723,7 @@ object Future { final def sequence[A, CC[X] <: IterableOnce[X], To](in: CC[Future[A]])(implicit bf: BuildFrom[CC[Future[A]], A, To], executor: ExecutionContext): Future[To] = in.iterator.foldLeft(successful(bf.newBuilder(in))) { (fr, fa) => fr.zipWith(fa)(Future.addToBuilderFun) - }.map(_.result())(if (executor.isInstanceOf[BatchingExecutor]) executor else parasitic) + }.map(_.result())(using if (executor.isInstanceOf[BatchingExecutor]) executor else parasitic) /** Asynchronously and non-blockingly returns a new `Future` to the result of the first future * in the list that is completed. This means no matter if it is completed as a success or as a failure. @@ -803,7 +803,7 @@ object Future { final def foldLeft[T, R](futures: scala.collection.immutable.Iterable[Future[T]])(zero: R)(op: (R, T) => R)(implicit executor: ExecutionContext): Future[R] = foldNext(futures.iterator, zero, op) - private[this] final def foldNext[T, R](i: Iterator[Future[T]], prevValue: R, op: (R, T) => R)(implicit executor: ExecutionContext): Future[R] = + private final def foldNext[T, R](i: Iterator[Future[T]], prevValue: R, op: (R, T) => R)(implicit executor: ExecutionContext): Future[R] = if (!i.hasNext) successful(prevValue) else i.next().flatMap { value => foldNext(i, op(prevValue, value), op) } @@ -828,7 +828,7 @@ object Future { // not removed in 2.13, to facilitate 2.11/2.12/2.13 cross-building; remove further down the line (see scala/scala#6319) def fold[T, R](futures: IterableOnce[Future[T]])(zero: R)(@deprecatedName("foldFun") op: (R, T) => R)(implicit executor: ExecutionContext): Future[R] = if (futures.isEmpty) successful(zero) - else sequence(futures)(ArrayBuffer, executor).map(_.foldLeft(zero)(op)) + else sequence(futures)(using ArrayBuffer, executor).map(_.foldLeft(zero)(op)) /** Initiates a non-blocking, asynchronous, fold over the supplied futures * where the fold-zero is the result value of the first `Future` in the collection. @@ -847,7 +847,7 @@ object Future { // not removed in 2.13, to facilitate 2.11/2.12/2.13 cross-building; remove further down the line (see scala/scala#6319) final def reduce[T, R >: T](futures: IterableOnce[Future[T]])(op: (R, T) => R)(implicit executor: ExecutionContext): Future[R] = if (futures.isEmpty) failed(new NoSuchElementException("reduce attempted on empty collection")) - else sequence(futures)(ArrayBuffer, executor).map(_ reduceLeft op) + else sequence(futures)(using ArrayBuffer, executor).map(_ reduceLeft op) /** Initiates a non-blocking, asynchronous, left reduction over the supplied futures * where the zero is the result value of the first `Future`. @@ -886,7 +886,7 @@ object Future { final def traverse[A, B, M[X] <: IterableOnce[X]](in: M[A])(fn: A => Future[B])(implicit bf: BuildFrom[M[A], B, M[B]], executor: ExecutionContext): Future[M[B]] = in.iterator.foldLeft(successful(bf.newBuilder(in))) { (fr, a) => fr.zipWith(fn(a))(Future.addToBuilderFun) - }.map(_.result())(if (executor.isInstanceOf[BatchingExecutor]) executor else parasitic) + }.map(_.result())(using if (executor.isInstanceOf[BatchingExecutor]) executor else parasitic) } @deprecated("Superseded by `scala.concurrent.Batchable`", "2.13.0") diff --git a/library/src/scala/concurrent/Promise.scala b/library/src/scala/concurrent/Promise.scala index 3c82b9e5920f..8bd1e920e6c6 100644 --- a/library/src/scala/concurrent/Promise.scala +++ b/library/src/scala/concurrent/Promise.scala @@ -71,7 +71,7 @@ trait Promise[T] { */ def completeWith(other: Future[T]): this.type = { if (other ne this.future) // this tryCompleteWith this doesn't make much sense - other.onComplete(this tryComplete _)(ExecutionContext.parasitic) + other.onComplete(this tryComplete _)(using ExecutionContext.parasitic) this } diff --git a/library/src/scala/concurrent/SyncChannel.scala b/library/src/scala/concurrent/SyncChannel.scala index 53fe27deb4fd..f0dd6c13e884 100644 --- a/library/src/scala/concurrent/SyncChannel.scala +++ b/library/src/scala/concurrent/SyncChannel.scala @@ -23,8 +23,8 @@ class SyncChannel[A] { private final val Signal = () private type Signal = Unit - private[this] var pendingWrites = List[(A, SyncVar[Signal])]() - private[this] var pendingReads = List[SyncVar[A]]() + private var pendingWrites = List[(A, SyncVar[Signal])]() + private var pendingReads = List[SyncVar[A]]() def write(data: A): Unit = { // create write request diff --git a/library/src/scala/concurrent/SyncVar.scala b/library/src/scala/concurrent/SyncVar.scala index ccb7d19f3bc7..7f7e2a24976a 100644 --- a/library/src/scala/concurrent/SyncVar.scala +++ b/library/src/scala/concurrent/SyncVar.scala @@ -22,8 +22,8 @@ import java.util.concurrent.TimeUnit */ @deprecated("Use `java.util.concurrent.LinkedBlockingQueue with capacity 1` instead.", since = "2.13.0") class SyncVar[A] { - private[this] var isDefined: Boolean = false - private[this] var value: A = _ + private var isDefined: Boolean = false + private var value: A = compiletime.uninitialized /** * Wait for this SyncVar to become defined and then get diff --git a/library/src/scala/concurrent/duration/Duration.scala b/library/src/scala/concurrent/duration/Duration.scala index 4fa495c8989c..1757c74d02a3 100644 --- a/library/src/scala/concurrent/duration/Duration.scala +++ b/library/src/scala/concurrent/duration/Duration.scala @@ -46,7 +46,7 @@ object Duration { def apply(length: Long, unit: String): FiniteDuration = new FiniteDuration(length, Duration.timeUnit(unit)) // Double stores 52 bits mantissa, but there is an implied '1' in front, making the limit 2^53 - // private[this] final val maxPreciseDouble = 9007199254740992d // not used after https://github.com/scala/scala/pull/9233 + // private final val maxPreciseDouble = 9007199254740992d // not used after https://github.com/scala/scala/pull/9233 /** * Parse String into Duration. Format is `""`, where @@ -75,12 +75,12 @@ object Duration { } // "ms milli millisecond" -> List("ms", "milli", "millis", "millisecond", "milliseconds") - private[this] def words(s: String) = (s.trim split "\\s+").toList - private[this] def expandLabels(labels: String): List[String] = { + private def words(s: String) = s.trim.split("\\s+").toList + private def expandLabels(labels: String): List[String] = { val hd :: rest = words(labels): @unchecked hd :: rest.flatMap(s => List(s, s + "s")) } - private[this] val timeUnitLabels = List( + private val timeUnitLabels = List( DAYS -> "d day", HOURS -> "h hr hour", MINUTES -> "m min minute", @@ -135,12 +135,12 @@ object Duration { fromNanos(nanos.round) } - private[this] final val ns_per_µs = 1000L - private[this] final val ns_per_ms = ns_per_µs * 1000 - private[this] final val ns_per_s = ns_per_ms * 1000 - private[this] final val ns_per_min = ns_per_s * 60 - private[this] final val ns_per_h = ns_per_min * 60 - private[this] final val ns_per_d = ns_per_h * 24 + private final val ns_per_µs = 1000L + private final val ns_per_ms = ns_per_µs * 1000 + private final val ns_per_s = ns_per_ms * 1000 + private final val ns_per_min = ns_per_s * 60 + private final val ns_per_h = ns_per_min * 60 + private final val ns_per_d = ns_per_h * 24 /** * Construct a finite duration from the given number of nanoseconds. The @@ -217,7 +217,7 @@ object Duration { final def isFinite = false - private[this] def fail(what: String) = throw new IllegalArgumentException(s"$what not allowed on infinite Durations") + private def fail(what: String) = throw new IllegalArgumentException(s"$what not allowed on infinite Durations") final def length: Long = fail("length") final def unit: TimeUnit = fail("unit") final def toNanos: Long = fail("toNanos") @@ -571,7 +571,7 @@ final class FiniteDuration(val length: Long, val unit: TimeUnit) extends Duratio import FiniteDuration._ import Duration._ - private[this] def bounded(max: Long) = -max <= length && length <= max + private def bounded(max: Long) = -max <= length && length <= max require(unit match { /* @@ -603,7 +603,7 @@ final class FiniteDuration(val length: Long, val unit: TimeUnit) extends Duratio */ def fromNow: Deadline = Deadline.now + this - private[this] def unitString = timeUnitName(unit) + ( if (length == 1) "" else "s" ) + private def unitString = timeUnitName(unit) + ( if (length == 1) "" else "s" ) override def toString: String = "" + length + " " + unitString def compare(other: Duration): Int = other match { @@ -612,12 +612,12 @@ final class FiniteDuration(val length: Long, val unit: TimeUnit) extends Duratio } // see https://www.securecoding.cert.org/confluence/display/java/NUM00-J.+Detect+or+prevent+integer+overflow - private[this] def safeAdd(a: Long, b: Long): Long = { + private def safeAdd(a: Long, b: Long): Long = { if ((b > 0) && (a > Long.MaxValue - b) || (b < 0) && (a < Long.MinValue - b)) throw new IllegalArgumentException("integer overflow") a + b } - private[this] def add(otherLength: Long, otherUnit: TimeUnit): FiniteDuration = { + private def add(otherLength: Long, otherUnit: TimeUnit): FiniteDuration = { val commonUnit = if (otherUnit.convert(1, unit) == 0) unit else otherUnit val totalLength = safeAdd(commonUnit.convert(length, unit), commonUnit.convert(otherLength, otherUnit)) new FiniteDuration(totalLength, commonUnit) @@ -644,7 +644,7 @@ final class FiniteDuration(val length: Long, val unit: TimeUnit) extends Duratio else Zero // if this is made a constant, then scalac will elide the conditional and always return +0.0, scala/bug#6331 - private[this] def minusZero = -0d + private def minusZero = -0d def /(divisor: Duration): Double = if (divisor.isFinite) toNanos.toDouble / divisor.toNanos else if (divisor eq Undefined) Double.NaN diff --git a/library/src/scala/concurrent/impl/ExecutionContextImpl.scala b/library/src/scala/concurrent/impl/ExecutionContextImpl.scala index 54fd2dc4795b..4a602d7d0785 100644 --- a/library/src/scala/concurrent/impl/ExecutionContextImpl.scala +++ b/library/src/scala/concurrent/impl/ExecutionContextImpl.scala @@ -19,7 +19,7 @@ import scala.concurrent.{ BlockContext, ExecutionContext, CanAwait, ExecutionCon private[scala] class ExecutionContextImpl private[impl] (final val executor: Executor, final val reporter: Throwable => Unit) extends ExecutionContextExecutor { require(executor ne null, "Executor must not be null") - override final def execute(runnable: Runnable): Unit = executor execute runnable + override final def execute(runnable: Runnable): Unit = executor.execute(runnable) override final def reportFailure(t: Throwable): Unit = reporter(t) } @@ -48,14 +48,14 @@ private[concurrent] object ExecutionContextImpl { def newThread(fjp: ForkJoinPool): ForkJoinWorkerThread = wire(new ForkJoinWorkerThread(fjp) with BlockContext { - private[this] final var isBlocked: Boolean = false // This is only ever read & written if this thread is the current thread + private final var isBlocked: Boolean = false // This is only ever read & written if this thread is the current thread final override def blockOn[T](thunk: => T)(implicit permission: CanAwait): T = if ((Thread.currentThread eq this) && !isBlocked && blockerPermits.tryAcquire()) { try { - val b: ForkJoinPool.ManagedBlocker with (() => T) = + val b: (ForkJoinPool.ManagedBlocker & (() => T)) = new ForkJoinPool.ManagedBlocker with (() => T) { - private[this] final var result: T = null.asInstanceOf[T] - private[this] final var done: Boolean = false + private final var result: T = null.asInstanceOf[T] + private final var done: Boolean = false final override def block(): Boolean = { if (!done) { result = thunk // If this throws then it will stop blocking. @@ -121,7 +121,7 @@ private[concurrent] object ExecutionContextImpl { case some => // This is a anonymous class extending a Java class, so we left inferred flexible types in the signatures. new ExecutionContextImpl(some, reporter) with ExecutionContextExecutorService { - private[this] final def asExecutorService: ExecutorService = executor.asInstanceOf[ExecutorService] + private final def asExecutorService: ExecutorService = executor.asInstanceOf[ExecutorService] final override def shutdown() = asExecutorService.shutdown() final override def shutdownNow() = asExecutorService.shutdownNow() final override def isShutdown = asExecutorService.isShutdown @@ -130,10 +130,10 @@ private[concurrent] object ExecutionContextImpl { final override def submit[T](callable: Callable[T]) = asExecutorService.submit(callable) final override def submit[T](runnable: Runnable, t: T) = asExecutorService.submit(runnable, t) final override def submit(runnable: Runnable) = asExecutorService.submit(runnable) - final override def invokeAll[T](callables: Collection[_ <: Callable[T]]) = asExecutorService.invokeAll(callables) - final override def invokeAll[T](callables: Collection[_ <: Callable[T]], l: Long, timeUnit: TimeUnit) = asExecutorService.invokeAll(callables, l, timeUnit) - final override def invokeAny[T](callables: Collection[_ <: Callable[T]]) = asExecutorService.invokeAny(callables) - final override def invokeAny[T](callables: Collection[_ <: Callable[T]], l: Long, timeUnit: TimeUnit) = asExecutorService.invokeAny(callables, l, timeUnit) + final override def invokeAll[T](callables: Collection[? <: Callable[T]]) = asExecutorService.invokeAll(callables) + final override def invokeAll[T](callables: Collection[? <: Callable[T]], l: Long, timeUnit: TimeUnit) = asExecutorService.invokeAll(callables, l, timeUnit) + final override def invokeAny[T](callables: Collection[? <: Callable[T]]) = asExecutorService.invokeAny(callables) + final override def invokeAny[T](callables: Collection[? <: Callable[T]], l: Long, timeUnit: TimeUnit) = asExecutorService.invokeAny(callables, l, timeUnit) } } } diff --git a/library/src/scala/concurrent/impl/FutureConvertersImpl.scala b/library/src/scala/concurrent/impl/FutureConvertersImpl.scala index 68c4293a439d..b19865e10be9 100644 --- a/library/src/scala/concurrent/impl/FutureConvertersImpl.scala +++ b/library/src/scala/concurrent/impl/FutureConvertersImpl.scala @@ -29,31 +29,31 @@ private[scala] object FutureConvertersImpl { // Ensure that completions of this future cannot hold the Scala Future's completer hostage - override def thenApply[U](fn: JFunction[_ >: T, _ <: U]): CompletableFuture[U] = thenApplyAsync(fn) + override def thenApply[U](fn: JFunction[? >: T, ? <: U]): CompletableFuture[U] = thenApplyAsync(fn) - override def thenAccept(fn: Consumer[_ >: T]): CompletableFuture[Void] = thenAcceptAsync(fn) + override def thenAccept(fn: Consumer[? >: T]): CompletableFuture[Void] = thenAcceptAsync(fn) override def thenRun(fn: Runnable): CompletableFuture[Void] = thenRunAsync(fn) - override def thenCombine[U, V](cs: CompletionStage[_ <: U], fn: BiFunction[_ >: T, _ >: U, _ <: V]): CompletableFuture[V] = thenCombineAsync(cs, fn) + override def thenCombine[U, V](cs: CompletionStage[? <: U], fn: BiFunction[? >: T, ? >: U, ? <: V]): CompletableFuture[V] = thenCombineAsync(cs, fn) - override def thenAcceptBoth[U](cs: CompletionStage[_ <: U], fn: BiConsumer[_ >: T, _ >: U]): CompletableFuture[Void] = thenAcceptBothAsync(cs, fn) + override def thenAcceptBoth[U](cs: CompletionStage[? <: U], fn: BiConsumer[? >: T, ? >: U]): CompletableFuture[Void] = thenAcceptBothAsync(cs, fn) - override def runAfterBoth(cs: CompletionStage[_], fn: Runnable): CompletableFuture[Void] = runAfterBothAsync(cs, fn) + override def runAfterBoth(cs: CompletionStage[?], fn: Runnable): CompletableFuture[Void] = runAfterBothAsync(cs, fn) - override def applyToEither[U](cs: CompletionStage[_ <: T], fn: JFunction[_ >: T, U]): CompletableFuture[U] = applyToEitherAsync(cs, fn) + override def applyToEither[U](cs: CompletionStage[? <: T], fn: JFunction[? >: T, U]): CompletableFuture[U] = applyToEitherAsync(cs, fn) - override def acceptEither(cs: CompletionStage[_ <: T], fn: Consumer[_ >: T]): CompletableFuture[Void] = acceptEitherAsync(cs, fn) + override def acceptEither(cs: CompletionStage[? <: T], fn: Consumer[? >: T]): CompletableFuture[Void] = acceptEitherAsync(cs, fn) - override def runAfterEither(cs: CompletionStage[_], fn: Runnable): CompletableFuture[Void] = runAfterEitherAsync(cs, fn) + override def runAfterEither(cs: CompletionStage[?], fn: Runnable): CompletableFuture[Void] = runAfterEitherAsync(cs, fn) - override def thenCompose[U](fn: JFunction[_ >: T, _ <: CompletionStage[U]]): CompletableFuture[U] = thenComposeAsync(fn) + override def thenCompose[U](fn: JFunction[? >: T, ? <: CompletionStage[U]]): CompletableFuture[U] = thenComposeAsync(fn) - override def whenComplete(fn: BiConsumer[_ >: T, _ >: Throwable]): CompletableFuture[T] = whenCompleteAsync(fn) + override def whenComplete(fn: BiConsumer[? >: T, ? >: Throwable]): CompletableFuture[T] = whenCompleteAsync(fn) - override def handle[U](fn: BiFunction[_ >: T, Throwable, _ <: U]): CompletableFuture[U] = handleAsync(fn) + override def handle[U](fn: BiFunction[? >: T, Throwable, ? <: U]): CompletableFuture[U] = handleAsync(fn) - override def exceptionally(fn: JFunction[Throwable, _ <: T]): CompletableFuture[T] = { + override def exceptionally(fn: JFunction[Throwable, ? <: T]): CompletableFuture[T] = { val cf = new CompletableFuture[T] whenCompleteAsync((t, e) => { if (e == null) cf.complete(t) diff --git a/library/src/scala/concurrent/impl/Promise.scala b/library/src/scala/concurrent/impl/Promise.scala index d9bf2879e155..81972e939f4f 100644 --- a/library/src/scala/concurrent/impl/Promise.scala +++ b/library/src/scala/concurrent/impl/Promise.scala @@ -16,6 +16,7 @@ import scala.language.`2.13` import scala.concurrent.{Batchable, CanAwait, ExecutionContext, ExecutionException, Future, TimeoutException} import scala.concurrent.duration.Duration import scala.annotation.{nowarn, switch, tailrec} +import scala.annotation.unchecked.uncheckedVariance import scala.util.control.{ControlThrowable, NonFatal} import scala.util.{Failure, Success, Try} import scala.runtime.NonLocalReturnControl @@ -34,7 +35,7 @@ import java.io.{IOException, NotSerializableException, ObjectInputStream, Object */ private[impl] final class CompletionLatch[T] extends AbstractQueuedSynchronizer with (Try[T] => Unit) { //@volatie not needed since we use acquire/release - /*@volatile*/ @annotation.stableNull private[this] var _result: Try[T] | Null = null + /*@volatile*/ @annotation.stableNull private var _result: Try[T] | Null = null final def result: Try[T] | Null = _result override protected def tryAcquireShared(ignored: Int): Int = if (getState != 0) 1 else -1 override protected def tryReleaseShared(ignore: Int): Boolean = { @@ -72,12 +73,12 @@ private[concurrent] object Promise { /** * The combination of traversing and possibly unlinking of a given `target` DefaultPromise. **/ - @inline @tailrec private[this] final def compressed(current: DefaultPromise[T], target: DefaultPromise[T], owner: DefaultPromise[T]): DefaultPromise[T] = { + @inline @tailrec private final def compressed(current: DefaultPromise[T], target: DefaultPromise[T], owner: DefaultPromise[T]): DefaultPromise[T] = { val value = target.get() - if (value.isInstanceOf[Callbacks[_]]) { + if (value.isInstanceOf[Callbacks[?]]) { if (compareAndSet(current, target)) target // Link else compressed(current = get(), target = target, owner = owner) // Retry - } else if (value.isInstanceOf[Link[_]]) compressed(current = current, target = value.asInstanceOf[Link[T]].get(), owner = owner) // Compress + } else if (value.isInstanceOf[Link[?]]) compressed(current = current, target = value.asInstanceOf[Link[T]].get(), owner = owner) // Compress else /*if (value.isInstanceOf[Try[T]])*/ { owner.unlink(value.asInstanceOf[Try[T]]) // Discard links owner @@ -90,7 +91,7 @@ private[concurrent] object Promise { * those values which makes sense in the context of Futures. **/ // requireNonNull is paramount to guard against null completions - private[this] final def resolve[T](value: Try[T]): Try[T] = + private final def resolve[T](value: Try[T]): Try[T] = if (requireNonNull(value).isInstanceOf[Success[T]]) value else { val t = value.asInstanceOf[Failure[T]].exception @@ -103,7 +104,7 @@ private[concurrent] object Promise { } // Left non-final to enable addition of extra fields by Java/Scala converters in scala-java8-compat. - class DefaultPromise[T] private[this] (initial: AnyRef) extends AtomicReference[AnyRef](initial) with scala.concurrent.Promise[T] with scala.concurrent.Future[T] with (Try[T] => Unit) { + class DefaultPromise[T] private (initial: AnyRef) extends AtomicReference[AnyRef](initial) with scala.concurrent.Promise[T] with scala.concurrent.Future[T] with (Try[T] => Unit) { /** * Constructs a new, completed, Promise. */ @@ -134,7 +135,7 @@ private[concurrent] object Promise { override final def zipWith[U, R](that: Future[U])(f: (T, U) => R)(implicit executor: ExecutionContext): Future[R] = { val state = get() - if (state.isInstanceOf[Try[_]]) { + if (state.isInstanceOf[Try[?]]) { if (state.asInstanceOf[Try[T]].isFailure) this.asInstanceOf[Future[R]] else { val l = state.asInstanceOf[Success[T]].get @@ -170,47 +171,47 @@ private[concurrent] object Promise { override final def foreach[U](f: T => U)(implicit executor: ExecutionContext): Unit = { val state = get() - if (!state.isInstanceOf[Failure[_]]) dispatchOrAddCallbacks(state, new Transformation[T, Unit](Xform_foreach, f, executor)) + if (!state.isInstanceOf[Failure[?]]) dispatchOrAddCallbacks(state, new Transformation[T, Unit](Xform_foreach, f, executor)) } override final def flatMap[S](f: T => Future[S])(implicit executor: ExecutionContext): Future[S] = { val state = get() - if (!state.isInstanceOf[Failure[_]]) dispatchOrAddCallbacks(state, new Transformation[T, S](Xform_flatMap, f, executor)) + if (!state.isInstanceOf[Failure[?]]) dispatchOrAddCallbacks(state, new Transformation[T, S](Xform_flatMap, f, executor)) else this.asInstanceOf[Future[S]] } override final def map[S](f: T => S)(implicit executor: ExecutionContext): Future[S] = { val state = get() - if (!state.isInstanceOf[Failure[_]]) dispatchOrAddCallbacks(state, new Transformation[T, S](Xform_map, f, executor)) + if (!state.isInstanceOf[Failure[?]]) dispatchOrAddCallbacks(state, new Transformation[T, S](Xform_map, f, executor)) else this.asInstanceOf[Future[S]] } override final def filter(p: T => Boolean)(implicit executor: ExecutionContext): Future[T] = { val state = get() - if (!state.isInstanceOf[Failure[_]]) dispatchOrAddCallbacks(state, new Transformation[T, T](Xform_filter, p, executor)) // Short-circuit if we get a Success + if (!state.isInstanceOf[Failure[?]]) dispatchOrAddCallbacks(state, new Transformation[T, T](Xform_filter, p, executor)) // Short-circuit if we get a Success else this } override final def collect[S](pf: PartialFunction[T, S])(implicit executor: ExecutionContext): Future[S] = { val state = get() - if (!state.isInstanceOf[Failure[_]]) dispatchOrAddCallbacks(state, new Transformation[T, S](Xform_collect, pf, executor)) // Short-circuit if we get a Success + if (!state.isInstanceOf[Failure[?]]) dispatchOrAddCallbacks(state, new Transformation[T, S](Xform_collect, pf, executor)) // Short-circuit if we get a Success else this.asInstanceOf[Future[S]] } override final def recoverWith[U >: T](pf: PartialFunction[Throwable, Future[U]])(implicit executor: ExecutionContext): Future[U] = { val state = get() - if (!state.isInstanceOf[Success[_]]) dispatchOrAddCallbacks(state, new Transformation[T, U](Xform_recoverWith, pf, executor)) // Short-circuit if we get a Failure + if (!state.isInstanceOf[Success[?]]) dispatchOrAddCallbacks(state, new Transformation[T, U](Xform_recoverWith, pf, executor)) // Short-circuit if we get a Failure else this.asInstanceOf[Future[U]] } override final def recover[U >: T](pf: PartialFunction[Throwable, U])(implicit executor: ExecutionContext): Future[U] = { val state = get() - if (!state.isInstanceOf[Success[_]]) dispatchOrAddCallbacks(state, new Transformation[T, U](Xform_recover, pf, executor)) // Short-circuit if we get a Failure + if (!state.isInstanceOf[Success[?]]) dispatchOrAddCallbacks(state, new Transformation[T, U](Xform_recover, pf, executor)) // Short-circuit if we get a Failure else this.asInstanceOf[Future[U]] } override final def mapTo[S](implicit tag: scala.reflect.ClassTag[S]): Future[S] = - if (!get().isInstanceOf[Failure[_]]) super[Future].mapTo[S](tag) // Short-circuit if we get a Success + if (!get().isInstanceOf[Failure[?]]) super[Future].mapTo[S](using tag) // Short-circuit if we get a Success else this.asInstanceOf[Future[S]] @@ -228,17 +229,17 @@ private[concurrent] object Promise { } override final def failed: Future[Throwable] = - if (!get().isInstanceOf[Success[_]]) super.failed + if (!get().isInstanceOf[Success[?]]) super.failed else Future.failedFailureFuture // Cached instance in case of already known success @tailrec override final def toString: String = { val state = get() - if (state.isInstanceOf[Try[_]]) "Future("+state+")" - else if (state.isInstanceOf[Link[_]]) state.asInstanceOf[Link[T]].promise(this).toString + if (state.isInstanceOf[Try[?]]) "Future("+state+")" + else if (state.isInstanceOf[Link[?]]) state.asInstanceOf[Link[T]].promise(this).toString else /*if (state.isInstanceOf[Callbacks[T]]) */ "Future()" } - private[this] final def tryAwait0(atMost: Duration): Try[T] | Null = + private final def tryAwait0(atMost: Duration): Try[T] | Null = if (atMost ne Duration.Undefined) { val v = value0 if (v ne null) v @@ -247,7 +248,7 @@ private[concurrent] object Promise { if (atMost <= Duration.Zero) null else { val l = new CompletionLatch[T]() - onComplete(l)(ExecutionContext.parasitic) + onComplete(l)(using ExecutionContext.parasitic) if (atMost.isFinite) l.tryAcquireSharedNanos(1, atMost.toNanos) @@ -279,25 +280,25 @@ private[concurrent] object Promise { @tailrec // returns null if not completed private final def value0: Try[T] | Null = { val state = get() - if (state.isInstanceOf[Try[_]]) state.asInstanceOf[Try[T]] - else if (state.isInstanceOf[Link[_]]) state.asInstanceOf[Link[T]].promise(this).value0 + if (state.isInstanceOf[Try[?]]) state.asInstanceOf[Try[T]] + else if (state.isInstanceOf[Link[?]]) state.asInstanceOf[Link[T]].promise(this).value0 else /*if (state.isInstanceOf[Callbacks[T]])*/ null } override final def tryComplete(value: Try[T]): Boolean = { val state = get() - if (state.isInstanceOf[Try[_]]) false + if (state.isInstanceOf[Try[?]]) false else tryComplete0(state, resolve(value)) } @tailrec // WARNING: important that the supplied Try really is resolve():d private[Promise] final def tryComplete0(state: AnyRef, resolved: Try[T]): Boolean = - if (state.isInstanceOf[Callbacks[_]]) { + if (state.isInstanceOf[Callbacks[?]]) { if (compareAndSet(state, resolved)) { if (state ne Noop) submitWithValue(state.asInstanceOf[Callbacks[T]], resolved) true } else tryComplete0(get(), resolved) - } else if (state.isInstanceOf[Link[_]]) { + } else if (state.isInstanceOf[Link[?]]) { val p = state.asInstanceOf[Link[T]].promise(this) // If this returns owner/this, we are in a completed link (p ne this) && p.tryComplete0(p.get(), resolved) // Use this to get tailcall optimization and avoid re-resolution } else /* if(state.isInstanceOf[Try[T]]) */ false @@ -305,10 +306,10 @@ private[concurrent] object Promise { override final def completeWith(other: Future[T]): this.type = { if (other ne this) { val state = get() - if (!state.isInstanceOf[Try[_]]) { - val resolved = if (other.isInstanceOf[DefaultPromise[_]]) other.asInstanceOf[DefaultPromise[T]].value0 else other.value.orNull + if (!state.isInstanceOf[Try[?]]) { + val resolved = if (other.isInstanceOf[DefaultPromise[?]]) other.asInstanceOf[DefaultPromise[T]].value0 else other.value.orNull if (resolved ne null) tryComplete0(state, resolved) - else other.onComplete(this)(ExecutionContext.parasitic) + else other.onComplete(this)(using ExecutionContext.parasitic) } } @@ -320,10 +321,10 @@ private[concurrent] object Promise { * to the root promise when linking two promises together. */ @tailrec private final def dispatchOrAddCallbacks[C <: Callbacks[T]](state: AnyRef, callbacks: C): C = - if (state.isInstanceOf[Try[_]]) { + if (state.isInstanceOf[Try[?]]) { submitWithValue(callbacks, state.asInstanceOf[Try[T]]) // invariant: callbacks should never be Noop here callbacks - } else if (state.isInstanceOf[Callbacks[_]]) { + } else if (state.isInstanceOf[Callbacks[?]]) { if(compareAndSet(state, if (state ne Noop) concatCallbacks(callbacks, state.asInstanceOf[Callbacks[T]]) else callbacks)) callbacks else dispatchOrAddCallbacks(get(), callbacks) } else /*if (state.isInstanceOf[Link[T]])*/ { @@ -331,29 +332,29 @@ private[concurrent] object Promise { p.dispatchOrAddCallbacks(p.get(), callbacks) } - @tailrec private def unregisterCallback(t: Transformation[_, _]): Unit = { + @tailrec private def unregisterCallback(t: Transformation[?, ?]): Unit = { val state = get() if (state eq t) { if (!compareAndSet(state, Noop)) unregisterCallback(t) - } else if (state.isInstanceOf[ManyCallbacks[_]]) { + } else if (state.isInstanceOf[ManyCallbacks[?]]) { if (!compareAndSet(state, removeCallback(state.asInstanceOf[ManyCallbacks[T]], t))) unregisterCallback(t) } } // IMPORTANT: Noop should never be passed in here, neither as left OR as right - @tailrec private[this] final def concatCallbacks(left: Callbacks[T], right: Callbacks[T]): Callbacks[T] = - if (left.isInstanceOf[Transformation[T,_]]) new ManyCallbacks[T](left.asInstanceOf[Transformation[T,_]], right) + @tailrec private final def concatCallbacks(left: Callbacks[T], right: Callbacks[T]): Callbacks[T] = + if (left.isInstanceOf[Transformation[T, ?]]) new ManyCallbacks[T](left.asInstanceOf[Transformation[T, ?]], right) else /*if (left.isInstanceOf[ManyCallbacks[T]) */ { // This should only happen when linking val m = left.asInstanceOf[ManyCallbacks[T]] concatCallbacks(m.rest, new ManyCallbacks(m.first, right)) } - @tailrec private[this] final def removeCallback(cs: Callbacks[T], t: Transformation[_, _], result: Callbacks[T] | Null = null): AnyRef = + @tailrec private final def removeCallback(cs: Callbacks[T], t: Transformation[?, ?], result: Callbacks[T] | Null = null): AnyRef = if (cs eq t) { if (result == null) Noop else result } - else if (cs.isInstanceOf[ManyCallbacks[_]]) { + else if (cs.isInstanceOf[ManyCallbacks[?]]) { val m = cs.asInstanceOf[ManyCallbacks[T]] if (m.first eq t) { if (result == null) m.rest @@ -364,13 +365,13 @@ private[concurrent] object Promise { // IMPORTANT: Noop should not be passed in here, `callbacks` cannot be null @tailrec - private[this] final def submitWithValue(callbacks: Callbacks[T], resolved: Try[T]): Unit = + private final def submitWithValue(callbacks: Callbacks[T], resolved: Try[T]): Unit = if(callbacks.isInstanceOf[ManyCallbacks[T]]) { val m: ManyCallbacks[T] = callbacks.asInstanceOf[ManyCallbacks[T]] m.first.submitWithValue(resolved) submitWithValue(m.rest, resolved) } else { - callbacks.asInstanceOf[Transformation[T, _]].submitWithValue(resolved) + callbacks.asInstanceOf[Transformation[T, ?]].submitWithValue(resolved) } /** Link this promise to the root of another promise. @@ -378,10 +379,10 @@ private[concurrent] object Promise { @tailrec private[concurrent] final def linkRootOf(target: DefaultPromise[T], link: Link[T] | Null): Unit = if (this ne target) { val state = get() - if (state.isInstanceOf[Try[_]]) { + if (state.isInstanceOf[Try[?]]) { if(!target.tryComplete0(target.get(), state.asInstanceOf[Try[T]])) throw new IllegalStateException("Cannot link completed promises together") - } else if (state.isInstanceOf[Callbacks[_]]) { + } else if (state.isInstanceOf[Callbacks[?]]) { val l = if (link ne null) link else new Link(target) val p = l.promise(this) if ((this ne p) && compareAndSet(state, l)) { @@ -397,7 +398,7 @@ private[concurrent] object Promise { **/ @tailrec private[concurrent] final def unlink(resolved: Try[T]): Unit = { val state = get() - if (state.isInstanceOf[Link[_]]) { + if (state.isInstanceOf[Link[?]]) { val next = if (compareAndSet(state, resolved)) state.asInstanceOf[Link[T]].get() else this next.unlink(resolved) } else tryComplete0(state, resolved) @@ -431,11 +432,11 @@ private[concurrent] object Promise { */ sealed trait Callbacks[-T] - final class ManyCallbacks[-T](final val first: Transformation[T,_], final val rest: Callbacks[T]) extends Callbacks[T] { + final class ManyCallbacks[-T](final val first: Transformation[T, ?], final val rest: Callbacks[T]) extends Callbacks[T] { override final def toString: String = "ManyCallbacks" } - private[this] final val Noop = new Transformation[Nothing, Nothing](Xform_noop, null: (Any => Any) | Null, ExecutionContext.parasitic) + private final val Noop = new Transformation[Nothing, Nothing](Xform_noop, null: (Any => Any) | Null, ExecutionContext.parasitic) /** * A Transformation[F, T] receives an F (it is a Callback[F]) and applies a transformation function to that F, @@ -443,13 +444,13 @@ private[concurrent] object Promise { * In order to conserve allocations, indirections, and avoid introducing bi/mega-morphicity the transformation * function's type parameters are erased, and the _xform tag will be used to reify them. **/ - final class Transformation[-F, T] private[this] ( - @annotation.stableNull private[this] final var _fun: (Any => Any) | Null, - @annotation.stableNull private[this] final var _ec: ExecutionContext | Null, - @annotation.stableNull private[this] final var _arg: Try[F] | Null, - private[this] final val _xform: Int + final class Transformation[-F, T] private ( + @annotation.stableNull private final var _fun: (Any => Any) | Null, + @annotation.stableNull private final var _ec: ExecutionContext | Null, + @annotation.stableNull private final var _arg: Try[F @uncheckedVariance] | Null, + private final val _xform: Int ) extends DefaultPromise[T]() with Callbacks[F] with Runnable with Batchable { - final def this(xform: Int, f: (_ => _) | Null, ec: ExecutionContext) = + final def this(xform: Int, f: (? => ?) | Null, ec: ExecutionContext) = this(f.asInstanceOf[(Any => Any) | Null], ec.prepare(): @nowarn("cat=deprecation"), null, xform) final def benefitsFromBatching: Boolean = _xform != Xform_onComplete && _xform != Xform_foreach @@ -473,7 +474,7 @@ private[concurrent] object Promise { this } - private[this] final def handleFailure(t: Throwable, e: ExecutionContext): Unit = { + private final def handleFailure(t: Throwable, e: ExecutionContext): Unit = { val wasInterrupted = t.isInstanceOf[InterruptedException] if (wasInterrupted || NonFatal(t)) { val completed = tryComplete0(get(), resolve(Failure(t))) @@ -494,7 +495,7 @@ private[concurrent] object Promise { _arg = null // see above _ec = null // see above try { - val resolvedResult: Try[_] | Null = + val resolvedResult: Try[?] | Null = (_xform: @switch) match { case Xform_noop => null @@ -503,14 +504,14 @@ private[concurrent] object Promise { case Xform_flatMap => if (v.isInstanceOf[Success[F]]) { val f = fun(v.get) - if (f.isInstanceOf[DefaultPromise[_]]) f.asInstanceOf[DefaultPromise[T]].linkRootOf(this, null) else completeWith(f.asInstanceOf[Future[T]]) + if (f.isInstanceOf[DefaultPromise[?]]) f.asInstanceOf[DefaultPromise[T]].linkRootOf(this, null) else completeWith(f.asInstanceOf[Future[T]]) null } else v case Xform_transform => resolve(fun(v).asInstanceOf[Try[T]]) case Xform_transformWith => val f = fun(v) - if (f.isInstanceOf[DefaultPromise[_]]) f.asInstanceOf[DefaultPromise[T]].linkRootOf(this, null) else completeWith(f.asInstanceOf[Future[T]]) + if (f.isInstanceOf[DefaultPromise[?]]) f.asInstanceOf[DefaultPromise[T]].linkRootOf(this, null) else completeWith(f.asInstanceOf[Future[T]]) null case Xform_foreach => v.foreach(fun) @@ -519,12 +520,12 @@ private[concurrent] object Promise { fun(v) null case Xform_recover => - if (v.isInstanceOf[Failure[_]]) resolve(v.recover(fun.asInstanceOf[PartialFunction[Throwable, F]])) else v //recover F=:=T + if (v.isInstanceOf[Failure[?]]) resolve(v.recover(fun.asInstanceOf[PartialFunction[Throwable, F]])) else v //recover F=:=T case Xform_recoverWith => if (v.isInstanceOf[Failure[F]]) { val f = fun.asInstanceOf[PartialFunction[Throwable, Future[T]]].applyOrElse(v.asInstanceOf[Failure[F]].exception, Future.recoverWithFailed) if (f ne Future.recoverWithFailedMarker) { - if (f.isInstanceOf[DefaultPromise[_]]) f.asInstanceOf[DefaultPromise[T]].linkRootOf(this, null) else completeWith(f.asInstanceOf[Future[T]]) + if (f.isInstanceOf[DefaultPromise[?]]) f.asInstanceOf[DefaultPromise[T]].linkRootOf(this, null) else completeWith(f.asInstanceOf[Future[T]]) null } else v } else v diff --git a/library/src/scala/concurrent/package.scala b/library/src/scala/concurrent/package.scala index 00a13bb66801..36d5b956a27b 100644 --- a/library/src/scala/concurrent/package.scala +++ b/library/src/scala/concurrent/package.scala @@ -123,7 +123,7 @@ package object concurrent { * @throws InterruptedException in the case that a wait within the blocking `body` was interrupted */ @throws(classOf[Exception]) - final def blocking[T](body: => T): T = BlockContext.current.blockOn(body)(scala.concurrent.AwaitPermission) + final def blocking[T](body: => T): T = BlockContext.current.blockOn(body)(using scala.concurrent.AwaitPermission) } package concurrent { @@ -176,7 +176,7 @@ package concurrent { if (atMost eq Duration.Undefined) Future.waitUndefinedError() // preserve semantics, see scala/scala#10972 else awaitable case _ => - blocking(awaitable.ready(atMost)(AwaitPermission)) + blocking(awaitable.ready(atMost)(using AwaitPermission)) } /** @@ -206,7 +206,7 @@ package concurrent { if (atMost eq Duration.Undefined) Future.waitUndefinedError() // preserve semantics, see scala/scala#10972 else v.get case _ => - blocking(awaitable.result(atMost)(AwaitPermission)) + blocking(awaitable.result(atMost)(using AwaitPermission)) } private object FutureValue { diff --git a/library/src/scala/io/BufferedSource.scala b/library/src/scala/io/BufferedSource.scala index d4cfee2db477..cc11013d6869 100644 --- a/library/src/scala/io/BufferedSource.scala +++ b/library/src/scala/io/BufferedSource.scala @@ -22,7 +22,7 @@ import scala.collection.mutable.StringBuilder * representation of a source file. */ class BufferedSource(inputStream: InputStream, bufferSize: Int)(implicit val codec: Codec) extends Source { - def this(inputStream: InputStream)(implicit codec: Codec) = this(inputStream, DefaultBufSize)(codec) + def this(inputStream: InputStream)(implicit codec: Codec) = this(inputStream, DefaultBufSize)(using codec) def reader() = new InputStreamReader(inputStream, codec.decoder) def bufferedReader() = new BufferedReader(reader(), bufferSize) @@ -31,8 +31,8 @@ class BufferedSource(inputStream: InputStream, bufferSize: Int)(implicit val cod // block of data to be read from the stream, which will then be lost // to getLines if it creates a new reader, even though next() was // never called on the original. - private[this] var charReaderCreated = false - private[this] lazy val charReader = { + private var charReaderCreated = false + private lazy val charReader = { charReaderCreated = true bufferedReader() } @@ -58,7 +58,7 @@ class BufferedSource(inputStream: InputStream, bufferSize: Int)(implicit val cod // immediately on the source. if (charReaderCreated && iter.hasNext) { val pb = new PushbackReader(charReader) - pb unread iter.next().toInt + pb.unread(iter.next().toInt) new BufferedReader(pb, bufferSize) } else charReader @@ -66,7 +66,7 @@ class BufferedSource(inputStream: InputStream, bufferSize: Int)(implicit val cod class BufferedLineIterator extends AbstractIterator[String] with Iterator[String] { - private[this] val lineReader = decachedReader + private val lineReader = decachedReader @annotation.stableNull var nextLine: String | Null = null override def hasNext = { diff --git a/library/src/scala/io/Codec.scala b/library/src/scala/io/Codec.scala index 62c875cf2b27..f1151e74c7fe 100644 --- a/library/src/scala/io/Codec.scala +++ b/library/src/scala/io/Codec.scala @@ -39,11 +39,11 @@ class Codec(val charSet: Charset) { // these variables allow configuring the Codec object, and then // all decoders and encoders retrieved from it will use these settings. - private[this] var _onMalformedInput: Action | Null = null - private[this] var _onUnmappableCharacter: Action | Null = null - private[this] var _encodingReplacement: Array[Byte] | Null = null - private[this] var _decodingReplacement: String | Null = null - private[this] var _onCodingException: Handler = e => throw e + private var _onMalformedInput: Action | Null = null + private var _onUnmappableCharacter: Action | Null = null + private var _encodingReplacement: Array[Byte] | Null = null + private var _decodingReplacement: String | Null = null + private var _onCodingException: Handler = e => throw e /** The name of the Codec. */ override def toString: String = name @@ -58,16 +58,16 @@ class Codec(val charSet: Charset) { def name: String = charSet.name def encoder: CharsetEncoder = { val enc = charSet.newEncoder() - if (_onMalformedInput ne null) enc onMalformedInput _onMalformedInput - if (_onUnmappableCharacter ne null) enc onUnmappableCharacter _onUnmappableCharacter - if (_encodingReplacement ne null) enc replaceWith _encodingReplacement + if (_onMalformedInput ne null) enc.onMalformedInput(_onMalformedInput) + if (_onUnmappableCharacter ne null) enc.onUnmappableCharacter(_onUnmappableCharacter) + if (_encodingReplacement ne null) enc.replaceWith(_encodingReplacement) enc } def decoder: CharsetDecoder = { val dec = charSet.newDecoder() - if (_onMalformedInput ne null) dec onMalformedInput _onMalformedInput - if (_onUnmappableCharacter ne null) dec onUnmappableCharacter _onUnmappableCharacter - if (_decodingReplacement ne null) dec replaceWith _decodingReplacement + if (_onMalformedInput ne null) dec.onMalformedInput(_onMalformedInput) + if (_onUnmappableCharacter ne null) dec.onUnmappableCharacter(_onUnmappableCharacter) + if (_decodingReplacement ne null) dec.replaceWith(_decodingReplacement) dec } @@ -95,7 +95,7 @@ object Codec extends LowPriorityCodecImplicits { def fileEncodingCodec: Codec = apply(scala.util.Properties.encodingString) def default: Codec = defaultCharsetCodec - def apply(encoding: String): Codec = new Codec(Charset forName encoding) + def apply(encoding: String): Codec = new Codec(Charset.forName(encoding)) def apply(charSet: Charset): Codec = new Codec(charSet) def apply(decoder: CharsetDecoder): Codec = { val _decoder = decoder @@ -106,9 +106,9 @@ object Codec extends LowPriorityCodecImplicits { def fromUTF8(bytes: Array[Byte]): Array[Char] = fromUTF8(bytes, 0, bytes.length) def fromUTF8(bytes: Array[Byte], offset: Int, len: Int): Array[Char] = { val bbuffer = java.nio.ByteBuffer.wrap(bytes, offset, len) - val cbuffer = UTF8.charSet decode bbuffer + val cbuffer = UTF8.charSet.decode(bbuffer) val chars = new Array[Char](cbuffer.remaining()) - cbuffer get chars + cbuffer.get(chars) chars } @@ -116,17 +116,17 @@ object Codec extends LowPriorityCodecImplicits { @migration("This method was previously misnamed `fromUTF8`. Converts from character sequence to Array[Byte].", "2.9.0") def toUTF8(cs: CharSequence): Array[Byte] = { val cbuffer = java.nio.CharBuffer.wrap(cs, 0, cs.length) - val bbuffer = UTF8.charSet encode cbuffer + val bbuffer = UTF8.charSet.encode(cbuffer) val bytes = new Array[Byte](bbuffer.remaining()) - bbuffer get bytes + bbuffer.get(bytes) bytes } def toUTF8(chars: Array[Char], offset: Int, len: Int): Array[Byte] = { val cbuffer = java.nio.CharBuffer.wrap(chars, offset, len) - val bbuffer = UTF8.charSet encode cbuffer + val bbuffer = UTF8.charSet.encode(cbuffer) val bytes = new Array[Byte](bbuffer.remaining()) - bbuffer get bytes + bbuffer.get(bytes) bytes } diff --git a/library/src/scala/io/Source.scala b/library/src/scala/io/Source.scala index 49c965d46bc8..35de2a30b06d 100644 --- a/library/src/scala/io/Source.scala +++ b/library/src/scala/io/Source.scala @@ -55,37 +55,37 @@ object Source { * filename. */ def fromFile(name: String)(implicit codec: Codec): BufferedSource = - fromFile(new JFile(name))(codec) + fromFile(new JFile(name))(using codec) /** creates Source from file with given name, using given encoding, setting * its description to filename. */ def fromFile(name: String, enc: String): BufferedSource = - fromFile(name)(Codec(enc)) + fromFile(name)(using Codec(enc)) /** creates `source` from file with given file `URI`. */ def fromFile(uri: URI)(implicit codec: Codec): BufferedSource = - fromFile(new JFile(uri))(codec) + fromFile(new JFile(uri))(using codec) /** creates Source from file with given file: URI */ def fromFile(uri: URI, enc: String): BufferedSource = - fromFile(uri)(Codec(enc)) + fromFile(uri)(using Codec(enc)) /** creates Source from file, using default character encoding, setting its * description to filename. */ def fromFile(file: JFile)(implicit codec: Codec): BufferedSource = - fromFile(file, Source.DefaultBufSize)(codec) + fromFile(file, Source.DefaultBufSize)(using codec) /** same as fromFile(file, enc, Source.DefaultBufSize) */ def fromFile(file: JFile, enc: String): BufferedSource = - fromFile(file)(Codec(enc)) + fromFile(file)(using Codec(enc)) def fromFile(file: JFile, enc: String, bufferSize: Int): BufferedSource = - fromFile(file, bufferSize)(Codec(enc)) + fromFile(file, bufferSize)(using Codec(enc)) /** Creates Source from `file`, using given character encoding, setting * its description to filename. Input is buffered in a buffer of size @@ -97,9 +97,9 @@ object Source { createBufferedSource( inputStream, bufferSize, - () => fromFile(file, bufferSize)(codec), + () => fromFile(file, bufferSize)(using codec), () => inputStream.close() - )(codec) withDescription s"file:${file.getAbsolutePath}" + )(using codec) withDescription s"file:${file.getAbsolutePath}" } /** Create a `Source` from array of bytes, decoding @@ -111,7 +111,7 @@ object Source { fromString(new String(bytes, codec.name)) def fromBytes(bytes: Array[Byte], enc: String): Source = - fromBytes(bytes)(Codec(enc)) + fromBytes(bytes)(using Codec(enc)) /** Create a `Source` from array of bytes, assuming * one byte per character (ISO-8859-1 encoding.) @@ -123,27 +123,27 @@ object Source { /** creates `Source` from file with given file: URI */ def fromURI(uri: URI)(implicit codec: Codec): BufferedSource = - fromFile(new JFile(uri))(codec) + fromFile(new JFile(uri))(using codec) /** same as fromURL(new URL(s))(Codec(enc)) */ def fromURL(s: String, enc: String): BufferedSource = - fromURL(s)(Codec(enc)) + fromURL(s)(using Codec(enc)) /** same as fromURL(new URL(s)) */ def fromURL(s: String)(implicit codec: Codec): BufferedSource = - fromURL(new URI(s).toURL)(codec) + fromURL(new URI(s).toURL)(using codec) /** same as fromInputStream(url.openStream())(Codec(enc)) */ def fromURL(url: URL, enc: String): BufferedSource = - fromURL(url)(Codec(enc)) + fromURL(url)(using Codec(enc)) /** same as fromInputStream(url.openStream())(codec) */ def fromURL(url: URL)(implicit codec: Codec): BufferedSource = - fromInputStream(url.openStream())(codec) + fromInputStream(url.openStream())(using codec) /** Reads data from inputStream with a buffered reader, using the encoding * in implicit parameter codec. @@ -162,16 +162,16 @@ object Source { close: (() => Unit) | Null = null )(implicit codec: Codec): BufferedSource = { // workaround for default arguments being unable to refer to other parameters - val resetFn = if (reset == null) () => createBufferedSource(inputStream, bufferSize, reset, close)(codec) else reset + val resetFn = if (reset == null) () => createBufferedSource(inputStream, bufferSize, reset, close)(using codec) else reset - new BufferedSource(inputStream, bufferSize)(codec) withReset resetFn withClose close + new BufferedSource(inputStream, bufferSize)(using codec) withReset resetFn withClose close } def fromInputStream(is: InputStream, enc: String): BufferedSource = - fromInputStream(is)(Codec(enc)) + fromInputStream(is)(using Codec(enc)) def fromInputStream(is: InputStream)(implicit codec: Codec): BufferedSource = - createBufferedSource(is, reset = () => fromInputStream(is)(codec), close = () => is.close())(codec) + createBufferedSource(is, reset = () => fromInputStream(is)(using codec), close = () => is.close())(using codec) /** Reads data from a classpath resource, using either a context classloader (default) or a passed one. * @@ -217,7 +217,7 @@ abstract class Source extends Iterator[Char] with Closeable { private def lineNum(line: Int): String = (getLines() drop (line - 1) take 1).mkString class LineIterator extends AbstractIterator[String] with Iterator[String] { - private[this] val sb = new StringBuilder + private val sb = new StringBuilder lazy val iter: BufferedIterator[Char] = Source.this.iter.buffered def isNewline(ch: Char): Boolean = ch == '\r' || ch == '\n' @@ -261,7 +261,7 @@ abstract class Source extends Iterator[Char] with Closeable { class Positioner(encoder: Position) { def this() = this(RelaxedPosition) /** the last character returned by next. */ - var ch: Char = _ + var ch: Char = compiletime.uninitialized /** position of last character returned by next */ var pos = 0 @@ -327,7 +327,7 @@ abstract class Source extends Iterator[Char] with Closeable { val line = Position line pos val col = Position column pos - out println "%s:%d:%d: %s%s%s^".format(descr, line, col, msg, lineNum(line), spaces(col - 1)) + out.println("%s:%d:%d: %s%s%s^".format(descr, line, col, msg, lineNum(line), spaces(col - 1))) } /** @@ -345,10 +345,10 @@ abstract class Source extends Iterator[Char] with Closeable { } @annotation.stableNull - private[this] var resetFunction: (() => Source) | Null = null + private var resetFunction: (() => Source) | Null = null @annotation.stableNull - private[this] var closeFunction: (() => Unit) | Null = null - private[this] var positioner: Positioner = RelaxedPositioner + private var closeFunction: (() => Unit) | Null = null + private var positioner: Positioner = RelaxedPositioner def withReset(f: (() => Source) | Null): this.type = { resetFunction = f diff --git a/library/src/scala/io/StdIn.scala b/library/src/scala/io/StdIn.scala index b79cbce83b3b..7ac7d994489f 100644 --- a/library/src/scala/io/StdIn.scala +++ b/library/src/scala/io/StdIn.scala @@ -38,7 +38,7 @@ private[scala] trait StdIn { * @return the string read from the default input */ def readLine(text: String, args: Any*): String = { - printf(text, args: _*) + printf(text, args*) out.flush() readLine() } @@ -105,7 +105,7 @@ private[scala] trait StdIn { if (s == null) throw new java.io.EOFException("Console has reached end of input") else - s charAt 0 + s.charAt(0) } /** Reads an int value from an entire line of the default input. diff --git a/library/src/scala/jdk/Accumulator.scala b/library/src/scala/jdk/Accumulator.scala index 612e317db497..1bfb0fc0be11 100644 --- a/library/src/scala/jdk/Accumulator.scala +++ b/library/src/scala/jdk/Accumulator.scala @@ -111,10 +111,10 @@ abstract class Accumulator[@specialized(Double, Int, Long) A, +CC[X] <: mutable. else 1 << 24 } - protected def efficientStepper[S <: Stepper[_]](implicit shape: StepperShape[A, S]): S with EfficientSplit + protected def efficientStepper[S <: Stepper[?]](implicit shape: StepperShape[A, S]): S & EfficientSplit - final override def stepper[S <: Stepper[_]](implicit shape: StepperShape[A, S]): S with EfficientSplit = - efficientStepper(shape) + final override def stepper[S <: Stepper[?]](implicit shape: StepperShape[A, S]): S & EfficientSplit = + efficientStepper(using shape) final override def length: Int = if (sizeLong < Int.MaxValue) sizeLong.toInt @@ -263,7 +263,7 @@ object Accumulator { * @return An $coll that contains the results of `n1 x n2` evaluations of `elem`. */ def fill[A, C](n1: Int, n2: Int)(elem: => A)(implicit canAccumulate: AccumulatorFactoryShape[A, C]): AnyAccumulator[C] = - fill(n1)(fill(n2)(elem)(canAccumulate))(AccumulatorFactoryShape.anyAccumulatorFactoryShape[C]) + fill(n1)(fill(n2)(elem)(using canAccumulate))(using AccumulatorFactoryShape.anyAccumulatorFactoryShape[C]) /** Produces a three-dimensional $coll containing the results of some element computation a number of times. * @param n1 the number of elements in the 1st dimension @@ -273,7 +273,7 @@ object Accumulator { * @return An $coll that contains the results of `n1 x n2 x n3` evaluations of `elem`. */ def fill[A, C](n1: Int, n2: Int, n3: Int)(elem: => A)(implicit canAccumulate: AccumulatorFactoryShape[A, C]): AnyAccumulator[AnyAccumulator[C]] = - fill(n1)(fill(n2, n3)(elem)(canAccumulate))(AccumulatorFactoryShape.anyAccumulatorFactoryShape[AnyAccumulator[C]]) + fill(n1)(fill(n2, n3)(elem)(using canAccumulate))(using AccumulatorFactoryShape.anyAccumulatorFactoryShape[AnyAccumulator[C]]) /** Produces a four-dimensional $coll containing the results of some element computation a number of times. * @param n1 the number of elements in the 1st dimension @@ -284,7 +284,7 @@ object Accumulator { * @return An $coll that contains the results of `n1 x n2 x n3 x n4` evaluations of `elem`. */ def fill[A, C](n1: Int, n2: Int, n3: Int, n4: Int)(elem: => A)(implicit canAccumulate: AccumulatorFactoryShape[A, C]): AnyAccumulator[AnyAccumulator[AnyAccumulator[C]]] = - fill(n1)(fill(n2, n3, n4)(elem)(canAccumulate))(AccumulatorFactoryShape.anyAccumulatorFactoryShape[AnyAccumulator[AnyAccumulator[C]]]) + fill(n1)(fill(n2, n3, n4)(elem)(using canAccumulate))(using AccumulatorFactoryShape.anyAccumulatorFactoryShape[AnyAccumulator[AnyAccumulator[C]]]) /** Produces a five-dimensional $coll containing the results of some element computation a number of times. * @param n1 the number of elements in the 1st dimension @@ -296,7 +296,7 @@ object Accumulator { * @return An $coll that contains the results of `n1 x n2 x n3 x n4 x n5` evaluations of `elem`. */ def fill[A, C](n1: Int, n2: Int, n3: Int, n4: Int, n5: Int)(elem: => A)(implicit canAccumulate: AccumulatorFactoryShape[A, C]): AnyAccumulator[AnyAccumulator[AnyAccumulator[AnyAccumulator[C]]]] = - fill(n1)(fill(n2, n3, n4, n5)(elem)(canAccumulate))(AccumulatorFactoryShape.anyAccumulatorFactoryShape[AnyAccumulator[AnyAccumulator[AnyAccumulator[C]]]]) + fill(n1)(fill(n2, n3, n4, n5)(elem)(using canAccumulate))(using AccumulatorFactoryShape.anyAccumulatorFactoryShape[AnyAccumulator[AnyAccumulator[AnyAccumulator[C]]]]) /** Produces an $coll containing values of a given function over a range of integer values starting from 0. * @param n The number of elements in the $coll @@ -314,7 +314,7 @@ object Accumulator { * for `0 <= i1 < n1` and `0 <= i2 < n2`. */ def tabulate[A, C](n1: Int, n2: Int)(f: (Int, Int) => A)(implicit canAccumulate: AccumulatorFactoryShape[A, C]): AnyAccumulator[C] = - tabulate(n1)(i1 => tabulate(n2)(f(i1, _))(canAccumulate))(AccumulatorFactoryShape.anyAccumulatorFactoryShape[C]) + tabulate(n1)(i1 => tabulate(n2)(f(i1, _))(using canAccumulate))(using AccumulatorFactoryShape.anyAccumulatorFactoryShape[C]) /** Produces a three-dimensional $coll containing values of a given function over ranges of integer values starting from 0. * @param n1 the number of elements in the 1st dimension @@ -325,7 +325,7 @@ object Accumulator { * for `0 <= i1 < n1`, `0 <= i2 < n2`, and `0 <= i3 < n3`. */ def tabulate[A, C](n1: Int, n2: Int, n3: Int)(f: (Int, Int, Int) => A)(implicit canAccumulate: AccumulatorFactoryShape[A, C]): AnyAccumulator[AnyAccumulator[C]] = - tabulate(n1)(i1 => tabulate(n2, n3)(f(i1, _, _))(canAccumulate))(AccumulatorFactoryShape.anyAccumulatorFactoryShape[AnyAccumulator[C]]) + tabulate(n1)(i1 => tabulate(n2, n3)(f(i1, _, _))(using canAccumulate))(using AccumulatorFactoryShape.anyAccumulatorFactoryShape[AnyAccumulator[C]]) /** Produces a four-dimensional $coll containing values of a given function over ranges of integer values starting from 0. * @param n1 the number of elements in the 1st dimension @@ -337,7 +337,7 @@ object Accumulator { * for `0 <= i1 < n1`, `0 <= i2 < n2`, `0 <= i3 < n3`, and `0 <= i4 < n4`. */ def tabulate[A, C](n1: Int, n2: Int, n3: Int, n4: Int)(f: (Int, Int, Int, Int) => A)(implicit canAccumulate: AccumulatorFactoryShape[A, C]): AnyAccumulator[AnyAccumulator[AnyAccumulator[C]]] = - tabulate(n1)(i1 => tabulate(n2, n3, n4)(f(i1, _, _, _))(canAccumulate))(AccumulatorFactoryShape.anyAccumulatorFactoryShape[AnyAccumulator[AnyAccumulator[C]]]) + tabulate(n1)(i1 => tabulate(n2, n3, n4)(f(i1, _, _, _))(using canAccumulate))(using AccumulatorFactoryShape.anyAccumulatorFactoryShape[AnyAccumulator[AnyAccumulator[C]]]) /** Produces a five-dimensional $coll containing values of a given function over ranges of integer values starting from 0. * @param n1 the number of elements in the 1st dimension @@ -350,7 +350,7 @@ object Accumulator { * for `0 <= i1 < n1`, `0 <= i2 < n2`, `0 <= i3 < n3`, `0 <= i4 < n4`, and `0 <= i5 < n5`. */ def tabulate[A, C](n1: Int, n2: Int, n3: Int, n4: Int, n5: Int)(f: (Int, Int, Int, Int, Int) => A)(implicit canAccumulate: AccumulatorFactoryShape[A, C]): AnyAccumulator[AnyAccumulator[AnyAccumulator[AnyAccumulator[C]]]] = - tabulate(n1)(i1 => tabulate(n2, n3, n4, n5)(f(i1, _, _, _, _))(canAccumulate))(AccumulatorFactoryShape.anyAccumulatorFactoryShape[AnyAccumulator[AnyAccumulator[AnyAccumulator[C]]]]) + tabulate(n1)(i1 => tabulate(n2, n3, n4, n5)(f(i1, _, _, _, _))(using canAccumulate))(using AccumulatorFactoryShape.anyAccumulatorFactoryShape[AnyAccumulator[AnyAccumulator[AnyAccumulator[C]]]]) /** Concatenates all argument collections into a single $coll. * diff --git a/library/src/scala/jdk/AnyAccumulator.scala b/library/src/scala/jdk/AnyAccumulator.scala index f2aa79b82853..68cb8204b2a9 100644 --- a/library/src/scala/jdk/AnyAccumulator.scala +++ b/library/src/scala/jdk/AnyAccumulator.scala @@ -33,9 +33,9 @@ final class AnyAccumulator[A] private[jdk] def cumulative(i: Int): Long = cumul(i) - override protected[this] def className: String = "AnyAccumulator" + override protected def className: String = "AnyAccumulator" - def efficientStepper[S <: Stepper[_]](implicit shape: StepperShape[A, S]): S with EfficientSplit = + def efficientStepper[S <: Stepper[?]](implicit shape: StepperShape[A, S]): S & EfficientSplit = shape.parUnbox(new AnyAccumulatorStepper[A](this.asInstanceOf[AnyAccumulator[A]])) private def expand(): Unit = { @@ -258,7 +258,7 @@ object AnyAccumulator extends collection.SeqFactory[AnyAccumulator] { def newBuilder[A]: mutable.Builder[A, AnyAccumulator[A]] = new AnyAccumulator[A] class SerializationProxy[A](@transient private val acc: AnyAccumulator[A]) extends Serializable { - @transient private var result: AnyAccumulator[AnyRef] = _ + @transient private var result: AnyAccumulator[AnyRef] = compiletime.uninitialized private def writeObject(out: ObjectOutputStream): Unit = { out.defaultWriteObject() @@ -284,7 +284,7 @@ object AnyAccumulator extends collection.SeqFactory[AnyAccumulator] { } } -private[jdk] class AnyAccumulatorStepper[A](private[this] val acc: AnyAccumulator[A]) extends AnyStepper[A] with EfficientSplit { +private[jdk] class AnyAccumulatorStepper[A](private val acc: AnyAccumulator[A]) extends AnyStepper[A] with EfficientSplit { import java.util.Spliterator._ private var h: Int = 0 @@ -353,7 +353,7 @@ private[jdk] class AnyAccumulatorStepper[A](private[this] val acc: AnyAccumulato override def spliterator[B >: A]: Spliterator[B] = new AnyStepper.AnyStepperSpliterator[B](this) { // Overridden for efficiency - override def tryAdvance(c: Consumer[_ >: B]): Boolean = { + override def tryAdvance(c: Consumer[? >: B]): Boolean = { if (N <= 0) false else { if (i >= n) loadMore() @@ -365,7 +365,7 @@ private[jdk] class AnyAccumulatorStepper[A](private[this] val acc: AnyAccumulato } // Overridden for efficiency - override def forEachRemaining(f: java.util.function.Consumer[_ >: B]): Unit = { + override def forEachRemaining(f: java.util.function.Consumer[? >: B]): Unit = { while (N > 0) { if (i >= n) loadMore() val i0 = i diff --git a/library/src/scala/jdk/DoubleAccumulator.scala b/library/src/scala/jdk/DoubleAccumulator.scala index 8a1aa8c88c88..3c85c835bbdf 100644 --- a/library/src/scala/jdk/DoubleAccumulator.scala +++ b/library/src/scala/jdk/DoubleAccumulator.scala @@ -33,9 +33,9 @@ final class DoubleAccumulator private[jdk] def cumulative(i: Int) = { val x = history(i); x(x.length-1).toLong } - override protected[this] def className: String = "DoubleAccumulator" + override protected def className: String = "DoubleAccumulator" - def efficientStepper[S <: Stepper[_]](implicit shape: StepperShape[Double, S]): S with EfficientSplit = { + def efficientStepper[S <: Stepper[?]](implicit shape: StepperShape[Double, S]): S & EfficientSplit = { val st = new DoubleAccumulatorStepper(this) val r = if (shape.shape == StepperShape.DoubleShape) st @@ -43,7 +43,7 @@ final class DoubleAccumulator assert(shape.shape == StepperShape.ReferenceShape, s"unexpected StepperShape: $shape") AnyStepper.ofParDoubleStepper(st) } - r.asInstanceOf[S with EfficientSplit] + r.asInstanceOf[S & EfficientSplit] } private def expand(): Unit = { @@ -338,7 +338,7 @@ object DoubleAccumulator extends collection.SpecificIterableFactory[Double, Doub override def newBuilder: DoubleAccumulator = new DoubleAccumulator class SerializationProxy[A](@transient private val acc: DoubleAccumulator) extends Serializable { - @transient private var result: DoubleAccumulator = _ + @transient private var result: DoubleAccumulator = compiletime.uninitialized private def writeObject(out: ObjectOutputStream): Unit = { out.defaultWriteObject() @@ -444,7 +444,7 @@ private[jdk] class DoubleAccumulatorStepper(private val acc: DoubleAccumulator) } // Overridden for efficiency - override def tryAdvance(c: Consumer[_ >: jl.Double]): Boolean = (c: AnyRef) match { + override def tryAdvance(c: Consumer[? >: jl.Double]): Boolean = (c: AnyRef) match { case ic: DoubleConsumer => tryAdvance(ic) case _ => if (N <= 0) false @@ -471,7 +471,7 @@ private[jdk] class DoubleAccumulatorStepper(private val acc: DoubleAccumulator) } // Overridden for efficiency - override def forEachRemaining(c: Consumer[_ >: jl.Double]): Unit = (c: AnyRef) match { + override def forEachRemaining(c: Consumer[? >: jl.Double]): Unit = (c: AnyRef) match { case ic: DoubleConsumer => forEachRemaining(ic) case _ => while (N > 0) { diff --git a/library/src/scala/jdk/IntAccumulator.scala b/library/src/scala/jdk/IntAccumulator.scala index 0a85b519ae63..839bfc899f3d 100644 --- a/library/src/scala/jdk/IntAccumulator.scala +++ b/library/src/scala/jdk/IntAccumulator.scala @@ -34,9 +34,9 @@ final class IntAccumulator private[jdk] def cumulative(i: Int) = { val x = history(i); x(x.length-2).toLong << 32 | (x(x.length-1)&0xFFFFFFFFL) } - override protected[this] def className: String = "IntAccumulator" + override protected def className: String = "IntAccumulator" - def efficientStepper[S <: Stepper[_]](implicit shape: StepperShape[Int, S]): S with EfficientSplit = { + def efficientStepper[S <: Stepper[?]](implicit shape: StepperShape[Int, S]): S & EfficientSplit = { val st = new IntAccumulatorStepper(this) val r = if (shape.shape == StepperShape.IntShape) st @@ -44,7 +44,7 @@ final class IntAccumulator assert(shape.shape == StepperShape.ReferenceShape, s"unexpected StepperShape: $shape") AnyStepper.ofParIntStepper(st) } - r.asInstanceOf[S with EfficientSplit] + r.asInstanceOf[S & EfficientSplit] } private def expand(): Unit = { @@ -344,7 +344,7 @@ object IntAccumulator extends collection.SpecificIterableFactory[Int, IntAccumul override def newBuilder: IntAccumulator = new IntAccumulator class SerializationProxy[A](@transient private val acc: IntAccumulator) extends Serializable { - @transient private var result: IntAccumulator = _ + @transient private var result: IntAccumulator = compiletime.uninitialized private def writeObject(out: ObjectOutputStream): Unit = { out.defaultWriteObject() @@ -450,7 +450,7 @@ private[jdk] class IntAccumulatorStepper(private val acc: IntAccumulator) extend } // Overridden for efficiency - override def tryAdvance(c: Consumer[_ >: jl.Integer]): Boolean = (c: AnyRef) match { + override def tryAdvance(c: Consumer[? >: jl.Integer]): Boolean = (c: AnyRef) match { case ic: IntConsumer => tryAdvance(ic) case _ => if (N <= 0) false @@ -477,7 +477,7 @@ private[jdk] class IntAccumulatorStepper(private val acc: IntAccumulator) extend } // Overridden for efficiency - override def forEachRemaining(c: Consumer[_ >: jl.Integer]): Unit = (c: AnyRef) match { + override def forEachRemaining(c: Consumer[? >: jl.Integer]): Unit = (c: AnyRef) match { case ic: IntConsumer => forEachRemaining(ic) case _ => while (N > 0) { diff --git a/library/src/scala/jdk/LongAccumulator.scala b/library/src/scala/jdk/LongAccumulator.scala index ee9ce79b0ba5..1d37eaac37bf 100644 --- a/library/src/scala/jdk/LongAccumulator.scala +++ b/library/src/scala/jdk/LongAccumulator.scala @@ -34,9 +34,9 @@ final class LongAccumulator private[jdk] def cumulative(i: Int) = { val x = history(i); x(x.length-1) } - override protected[this] def className: String = "LongAccumulator" + override protected def className: String = "LongAccumulator" - def efficientStepper[S <: Stepper[_]](implicit shape: StepperShape[Long, S]): S with EfficientSplit = { + def efficientStepper[S <: Stepper[?]](implicit shape: StepperShape[Long, S]): S & EfficientSplit = { val st = new LongAccumulatorStepper(this) val r = if (shape.shape == StepperShape.LongShape) st @@ -44,7 +44,7 @@ final class LongAccumulator assert(shape.shape == StepperShape.ReferenceShape, s"unexpected StepperShape: $shape") AnyStepper.ofParLongStepper(st) } - r.asInstanceOf[S with EfficientSplit] + r.asInstanceOf[S & EfficientSplit] } private def expand(): Unit = { @@ -339,7 +339,7 @@ object LongAccumulator extends collection.SpecificIterableFactory[Long, LongAccu override def newBuilder: LongAccumulator = new LongAccumulator class SerializationProxy[A](@transient private val acc: LongAccumulator) extends Serializable { - @transient private var result: LongAccumulator = _ + @transient private var result: LongAccumulator = compiletime.uninitialized private def writeObject(out: ObjectOutputStream): Unit = { out.defaultWriteObject() @@ -445,7 +445,7 @@ private[jdk] class LongAccumulatorStepper(private val acc: LongAccumulator) exte } // Overridden for efficiency - override def tryAdvance(c: Consumer[_ >: jl.Long]): Boolean = (c: AnyRef) match { + override def tryAdvance(c: Consumer[? >: jl.Long]): Boolean = (c: AnyRef) match { case ic: LongConsumer => tryAdvance(ic) case _ => if (N <= 0) false @@ -472,7 +472,7 @@ private[jdk] class LongAccumulatorStepper(private val acc: LongAccumulator) exte } // Overridden for efficiency - override def forEachRemaining(c: Consumer[_ >: jl.Long]): Unit = (c: AnyRef) match { + override def forEachRemaining(c: Consumer[? >: jl.Long]): Unit = (c: AnyRef) match { case ic: LongConsumer => forEachRemaining(ic) case _ => while (N > 0) { diff --git a/library/src/scala/jdk/javaapi/FutureConverters.scala b/library/src/scala/jdk/javaapi/FutureConverters.scala index c1538e8d1c31..02f8f3ef851d 100644 --- a/library/src/scala/jdk/javaapi/FutureConverters.scala +++ b/library/src/scala/jdk/javaapi/FutureConverters.scala @@ -52,7 +52,7 @@ object FutureConverters { case c: CompletionStage[T @unchecked] => c case _ => val cf = new CF[T](f) - f.onComplete(cf)(ExecutionContext.parasitic) + f.onComplete(cf)(using ExecutionContext.parasitic) cf } } diff --git a/library/src/scala/math/BigDecimal.scala b/library/src/scala/math/BigDecimal.scala index 25d5f55a55d9..969829af8385 100644 --- a/library/src/scala/math/BigDecimal.scala +++ b/library/src/scala/math/BigDecimal.scala @@ -27,12 +27,12 @@ object BigDecimal { private final val maximumHashScale = 4934 // Quit maintaining hash identity with BigInt beyond this scale private final val hashCodeNotComputed = 0x5D50690F // Magic value (happens to be "BigDecimal" old MurmurHash3 value) private final val deci2binary = 3.3219280948873626 // Ratio of log(10) to log(2) - private[this] val minCached = -512 - private[this] val maxCached = 512 + private val minCached = -512 + private val maxCached = 512 val defaultMathContext: MathContext = MathContext.DECIMAL128 /** Cache only for defaultMathContext using BigDecimals in a small range. */ - private[this] lazy val cache = new Array[BigDecimal](maxCached - minCached + 1) + private lazy val cache = new Array[BigDecimal](maxCached - minCached + 1) object RoundingMode extends Enumeration { // Annoying boilerplate to ensure consistency with java.math.RoundingMode @@ -136,7 +136,7 @@ object BigDecimal { * @param d the specified double value * @return the constructed `BigDecimal` */ - def valueOf(d: Double): BigDecimal = apply(BigDec valueOf d) + def valueOf(d: Double): BigDecimal = apply(BigDec.valueOf(d)) /** Constructs a `BigDecimal` using the java BigDecimal static * valueOf constructor. @@ -476,7 +476,7 @@ extends ScalaNumber with ScalaNumericConversions with Serializable with Ordered[ /** Compares this BigDecimal with the specified BigDecimal */ - def compare (that: BigDecimal): Int = this.bigDecimal compareTo that.bigDecimal + def compare (that: BigDecimal): Int = this.bigDecimal.compareTo(that.bigDecimal) /** Addition of BigDecimals */ @@ -563,13 +563,13 @@ extends ScalaNumber with ScalaNumericConversions with Serializable with Ordered[ * preserving its own MathContext for future operations. */ def round(mc: MathContext): BigDecimal = { - val r = this.bigDecimal round mc + val r = this.bigDecimal.round(mc) if (r eq bigDecimal) this else new BigDecimal(r, this.mc) } /** Returns a `BigDecimal` rounded according to its own `MathContext` */ def rounded: BigDecimal = { - val r = bigDecimal round mc + val r = bigDecimal.round(mc) if (r eq bigDecimal) this else new BigDecimal(r, mc) } @@ -583,7 +583,7 @@ extends ScalaNumber with ScalaNumericConversions with Serializable with Ordered[ /** Returns a new BigDecimal based on the supplied MathContext, rounded as needed. */ - def apply(mc: MathContext): BigDecimal = new BigDecimal(this.bigDecimal round mc, mc) + def apply(mc: MathContext): BigDecimal = new BigDecimal(this.bigDecimal.round(mc), mc) /** Returns a `BigDecimal` whose scale is the specified value, and whose value is * numerically equal to this BigDecimal's. diff --git a/library/src/scala/math/BigInt.scala b/library/src/scala/math/BigInt.scala index 76c4a7caf67f..429c03793989 100644 --- a/library/src/scala/math/BigInt.scala +++ b/library/src/scala/math/BigInt.scala @@ -26,11 +26,11 @@ object BigInt { private val longMinValueBigInteger = BigInteger.valueOf(Long.MinValue) private val longMinValue = new BigInt(longMinValueBigInteger, Long.MinValue) - private[this] val minCached = -1024 - private[this] val maxCached = 1024 - private[this] val cache = new Array[BigInt](maxCached - minCached + 1) + private val minCached = -1024 + private val maxCached = 1024 + private val cache = new Array[BigInt](maxCached - minCached + 1) - private[this] def getCached(i: Int): BigInt = { + private def getCached(i: Int): BigInt = { val offset = i - minCached var n = cache(offset) if (n eq null) { @@ -236,7 +236,7 @@ final class BigInt private ( else bigInteger.## /** Compares this BigInt with the specified value for equality. */ - @nowarn("cat=other-non-cooperative-equals") + // @nowarn("cat=other-non-cooperative-equals") TODO: Implement the category override def equals(that: Any): Boolean = that match { case that: BigInt => this equals that case that: BigDecimal => that equals this @@ -284,7 +284,7 @@ final class BigInt private ( */ private def bitLengthOverflow = { val shifted = bigInteger.shiftRight(Int.MaxValue) - (shifted.signum != 0) && !(shifted equals BigInt.minusOne) + (shifted.signum != 0) && !(shifted.equals(BigInt.minusOne)) } @deprecated("isWhole on an integer type is always true", "2.12.15") @@ -434,7 +434,7 @@ final class BigInt private ( if (that.longEncoding) { if (that._long == 0) return this.abs // if (that._long == Long.MinValue) return this gcd (-that) - val red = (this._bigInteger.nn mod BigInteger.valueOf(that._long.abs)).longValue() + val red = (this._bigInteger.nn.mod(BigInteger.valueOf(that._long.abs))).longValue() if (red == 0) return that.abs BigInt(BigInt.longGcd(that._long.abs, red)) } else BigInt(this.bigInteger.gcd(that.bigInteger)) diff --git a/library/src/scala/math/Equiv.scala b/library/src/scala/math/Equiv.scala index 4c708783f20a..39118b2a88ec 100644 --- a/library/src/scala/math/Equiv.scala +++ b/library/src/scala/math/Equiv.scala @@ -248,7 +248,7 @@ object Equiv extends LowPriorityEquiv { implicit def Option[T](implicit eqv: Equiv[T]): Equiv[Option[T]] = new OptionEquiv[T](eqv) - private[this] final class OptionEquiv[T](private val eqv: Equiv[T]) extends Equiv[Option[T]] { + private final class OptionEquiv[T](private val eqv: Equiv[T]) extends Equiv[Option[T]] { def equiv(x: Option[T], y: Option[T]): Boolean = (x, y) match { case (None, None) => true case (Some(x), Some(y)) => eqv.equiv(x, y) @@ -266,7 +266,7 @@ object Equiv extends LowPriorityEquiv { implicit def Tuple2[T1, T2](implicit eqv1: Equiv[T1], eqv2: Equiv[T2]): Equiv[(T1, T2)] = new Tuple2Equiv(eqv1, eqv2) - private[this] final class Tuple2Equiv[T1, T2](private val eqv1: Equiv[T1], + private final class Tuple2Equiv[T1, T2](private val eqv1: Equiv[T1], private val eqv2: Equiv[T2]) extends Equiv[(T1, T2)] { def equiv(x: (T1, T2), y: (T1, T2)): Boolean = eqv1.equiv(x._1, y._1) && @@ -285,7 +285,7 @@ object Equiv extends LowPriorityEquiv { implicit def Tuple3[T1, T2, T3](implicit eqv1: Equiv[T1], eqv2: Equiv[T2], eqv3: Equiv[T3]) : Equiv[(T1, T2, T3)] = new Tuple3Equiv(eqv1, eqv2, eqv3) - private[this] final class Tuple3Equiv[T1, T2, T3](private val eqv1: Equiv[T1], + private final class Tuple3Equiv[T1, T2, T3](private val eqv1: Equiv[T1], private val eqv2: Equiv[T2], private val eqv3: Equiv[T3]) extends Equiv[(T1, T2, T3)] { def equiv(x: (T1, T2, T3), y: (T1, T2, T3)): Boolean = @@ -307,7 +307,7 @@ object Equiv extends LowPriorityEquiv { implicit def Tuple4[T1, T2, T3, T4](implicit eqv1: Equiv[T1], eqv2: Equiv[T2], eqv3: Equiv[T3], eqv4: Equiv[T4]) : Equiv[(T1, T2, T3, T4)] = new Tuple4Equiv(eqv1, eqv2, eqv3, eqv4) - private[this] final class Tuple4Equiv[T1, T2, T3, T4](private val eqv1: Equiv[T1], + private final class Tuple4Equiv[T1, T2, T3, T4](private val eqv1: Equiv[T1], private val eqv2: Equiv[T2], private val eqv3: Equiv[T3], private val eqv4: Equiv[T4]) @@ -333,7 +333,7 @@ object Equiv extends LowPriorityEquiv { implicit def Tuple5[T1, T2, T3, T4, T5](implicit eqv1: Equiv[T1], eqv2: Equiv[T2], eqv3: Equiv[T3], eqv4: Equiv[T4], eqv5: Equiv[T5]): Equiv[(T1, T2, T3, T4, T5)] = new Tuple5Equiv(eqv1, eqv2, eqv3, eqv4, eqv5) - private[this] final class Tuple5Equiv[T1, T2, T3, T4, T5](private val eqv1: Equiv[T1], + private final class Tuple5Equiv[T1, T2, T3, T4, T5](private val eqv1: Equiv[T1], private val eqv2: Equiv[T2], private val eqv3: Equiv[T3], private val eqv4: Equiv[T4], @@ -362,7 +362,7 @@ object Equiv extends LowPriorityEquiv { implicit def Tuple6[T1, T2, T3, T4, T5, T6](implicit eqv1: Equiv[T1], eqv2: Equiv[T2], eqv3: Equiv[T3], eqv4: Equiv[T4], eqv5: Equiv[T5], eqv6: Equiv[T6]): Equiv[(T1, T2, T3, T4, T5, T6)] = new Tuple6Equiv(eqv1, eqv2, eqv3, eqv4, eqv5, eqv6) - private[this] final class Tuple6Equiv[T1, T2, T3, T4, T5, T6](private val eqv1: Equiv[T1], + private final class Tuple6Equiv[T1, T2, T3, T4, T5, T6](private val eqv1: Equiv[T1], private val eqv2: Equiv[T2], private val eqv3: Equiv[T3], private val eqv4: Equiv[T4], @@ -394,7 +394,7 @@ object Equiv extends LowPriorityEquiv { implicit def Tuple7[T1, T2, T3, T4, T5, T6, T7](implicit eqv1: Equiv[T1], eqv2: Equiv[T2], eqv3: Equiv[T3], eqv4: Equiv[T4], eqv5: Equiv[T5], eqv6: Equiv[T6], eqv7: Equiv[T7]): Equiv[(T1, T2, T3, T4, T5, T6, T7)] = new Tuple7Equiv(eqv1, eqv2, eqv3, eqv4, eqv5, eqv6, eqv7) - private[this] final class Tuple7Equiv[T1, T2, T3, T4, T5, T6, T7](private val eqv1: Equiv[T1], + private final class Tuple7Equiv[T1, T2, T3, T4, T5, T6, T7](private val eqv1: Equiv[T1], private val eqv2: Equiv[T2], private val eqv3: Equiv[T3], private val eqv4: Equiv[T4], @@ -429,7 +429,7 @@ object Equiv extends LowPriorityEquiv { implicit def Tuple8[T1, T2, T3, T4, T5, T6, T7, T8](implicit eqv1: Equiv[T1], eqv2: Equiv[T2], eqv3: Equiv[T3], eqv4: Equiv[T4], eqv5: Equiv[T5], eqv6: Equiv[T6], eqv7: Equiv[T7], eqv8: Equiv[T8]): Equiv[(T1, T2, T3, T4, T5, T6, T7, T8)] = new Tuple8Equiv(eqv1, eqv2, eqv3, eqv4, eqv5, eqv6, eqv7, eqv8) - private[this] final class Tuple8Equiv[T1, T2, T3, T4, T5, T6, T7, T8](private val eqv1: Equiv[T1], + private final class Tuple8Equiv[T1, T2, T3, T4, T5, T6, T7, T8](private val eqv1: Equiv[T1], private val eqv2: Equiv[T2], private val eqv3: Equiv[T3], private val eqv4: Equiv[T4], @@ -467,7 +467,7 @@ object Equiv extends LowPriorityEquiv { implicit def Tuple9[T1, T2, T3, T4, T5, T6, T7, T8, T9](implicit eqv1: Equiv[T1], eqv2: Equiv[T2], eqv3: Equiv[T3], eqv4: Equiv[T4], eqv5: Equiv[T5], eqv6: Equiv[T6], eqv7: Equiv[T7], eqv8 : Equiv[T8], eqv9: Equiv[T9]): Equiv[(T1, T2, T3, T4, T5, T6, T7, T8, T9)] = new Tuple9Equiv(eqv1, eqv2, eqv3, eqv4, eqv5, eqv6, eqv7, eqv8, eqv9) - private[this] final class Tuple9Equiv[T1, T2, T3, T4, T5, T6, T7, T8, T9](private val eqv1: Equiv[T1], + private final class Tuple9Equiv[T1, T2, T3, T4, T5, T6, T7, T8, T9](private val eqv1: Equiv[T1], private val eqv2: Equiv[T2], private val eqv3: Equiv[T3], private val eqv4: Equiv[T4], diff --git a/library/src/scala/math/Ordering.scala b/library/src/scala/math/Ordering.scala index e8d94a564665..df6a505235d3 100644 --- a/library/src/scala/math/Ordering.scala +++ b/library/src/scala/math/Ordering.scala @@ -125,7 +125,7 @@ trait Ordering[T] extends Comparator[T] with PartialOrdering[T] with Serializabl * Implementations should only override this method if they are overriding * [[reverse]] as well. */ - def isReverseOf(other: Ordering[_]): Boolean = other match { + def isReverseOf(other: Ordering[?]): Boolean = other match { case that: Ordering.Reverse[_] => that.outer == this case _ => false } @@ -207,7 +207,7 @@ trait Ordering[T] extends Comparator[T] with PartialOrdering[T] with Serializabl trait LowPriorityOrderingImplicits { - type AsComparable[A] = A => Comparable[_ >: A] + type AsComparable[A] = A => Comparable[? >: A] /** This would conflict with all the nice implicit Orderings * available, but thanks to the magic of prioritized implicits @@ -238,15 +238,15 @@ object Ordering extends LowPriorityOrderingImplicits { /** An ordering which caches the value of its reverse. */ sealed trait CachedReverse[T] extends Ordering[T] { - private[this] val _reverse = super.reverse + private val _reverse = super.reverse override final def reverse: Ordering[T] = _reverse - override final def isReverseOf(other: Ordering[_]): Boolean = other eq _reverse + override final def isReverseOf(other: Ordering[?]): Boolean = other eq _reverse } /** A reverse ordering */ private final class Reverse[T](private[Ordering] val outer: Ordering[T]) extends Ordering[T] { override def reverse: Ordering[T] = outer - override def isReverseOf(other: Ordering[_]): Boolean = other == outer + override def isReverseOf(other: Ordering[?]): Boolean = other == outer def compare(x: T, y: T): Int = outer.compare(y, x) override def lteq(x: T, y: T): Boolean = outer.lteq(y, x) @@ -637,7 +637,7 @@ object Ordering extends LowPriorityOrderingImplicits { new Tuple2Ordering(ord1, ord2) @SerialVersionUID(4945084135299531202L) - private[this] final class Tuple2Ordering[T1, T2](private val ord1: Ordering[T1], + private final class Tuple2Ordering[T1, T2](private val ord1: Ordering[T1], private val ord2: Ordering[T2]) extends Ordering[(T1, T2)] { def compare(x: (T1, T2), y: (T1, T2)): Int = { val compare1 = ord1.compare(x._1, y._1) @@ -659,7 +659,7 @@ object Ordering extends LowPriorityOrderingImplicits { new Tuple3Ordering(ord1, ord2, ord3) @SerialVersionUID(-5367223704121832335L) - private[this] final class Tuple3Ordering[T1, T2, T3](private val ord1: Ordering[T1], + private final class Tuple3Ordering[T1, T2, T3](private val ord1: Ordering[T1], private val ord2: Ordering[T2], private val ord3: Ordering[T3]) extends Ordering[(T1, T2, T3)] { def compare(x: (T1, T2, T3), y: (T1, T2, T3)): Int = { @@ -685,7 +685,7 @@ object Ordering extends LowPriorityOrderingImplicits { new Tuple4Ordering(ord1, ord2, ord3, ord4) @SerialVersionUID(-6055313861145218178L) - private[this] final class Tuple4Ordering[T1, T2, T3, T4](private val ord1: Ordering[T1], + private final class Tuple4Ordering[T1, T2, T3, T4](private val ord1: Ordering[T1], private val ord2: Ordering[T2], private val ord3: Ordering[T3], private val ord4: Ordering[T4]) @@ -716,7 +716,7 @@ object Ordering extends LowPriorityOrderingImplicits { new Tuple5Ordering(ord1, ord2, ord3, ord4, ord5) @SerialVersionUID(-5517329921227646061L) - private[this] final class Tuple5Ordering[T1, T2, T3, T4, T5](private val ord1: Ordering[T1], + private final class Tuple5Ordering[T1, T2, T3, T4, T5](private val ord1: Ordering[T1], private val ord2: Ordering[T2], private val ord3: Ordering[T3], private val ord4: Ordering[T4], @@ -751,7 +751,7 @@ object Ordering extends LowPriorityOrderingImplicits { implicit def Tuple6[T1, T2, T3, T4, T5, T6](implicit ord1: Ordering[T1], ord2: Ordering[T2], ord3: Ordering[T3], ord4: Ordering[T4], ord5: Ordering[T5], ord6: Ordering[T6]): Ordering[(T1, T2, T3, T4, T5, T6)] = new Tuple6Ordering(ord1, ord2, ord3, ord4, ord5, ord6) - private[this] final class Tuple6Ordering[T1, T2, T3, T4, T5, T6](private val ord1: Ordering[T1], + private final class Tuple6Ordering[T1, T2, T3, T4, T5, T6](private val ord1: Ordering[T1], private val ord2: Ordering[T2], private val ord3: Ordering[T3], private val ord4: Ordering[T4], @@ -790,7 +790,7 @@ object Ordering extends LowPriorityOrderingImplicits { new Tuple7Ordering(ord1, ord2, ord3, ord4, ord5, ord6, ord7) @SerialVersionUID(1253188205893682451L) - private[this] final class Tuple7Ordering[T1, T2, T3, T4, T5, T6, T7](private val ord1: Ordering[T1], + private final class Tuple7Ordering[T1, T2, T3, T4, T5, T6, T7](private val ord1: Ordering[T1], private val ord2: Ordering[T2], private val ord3: Ordering[T3], private val ord4: Ordering[T4], @@ -833,7 +833,7 @@ object Ordering extends LowPriorityOrderingImplicits { implicit def Tuple8[T1, T2, T3, T4, T5, T6, T7, T8](implicit ord1: Ordering[T1], ord2: Ordering[T2], ord3: Ordering[T3], ord4: Ordering[T4], ord5: Ordering[T5], ord6: Ordering[T6], ord7: Ordering[T7], ord8: Ordering[T8]): Ordering[(T1, T2, T3, T4, T5, T6, T7, T8)] = new Tuple8Ordering(ord1, ord2, ord3, ord4, ord5, ord6, ord7, ord8) - private[this] final class Tuple8Ordering[T1, T2, T3, T4, T5, T6, T7, T8](private val ord1: Ordering[T1], + private final class Tuple8Ordering[T1, T2, T3, T4, T5, T6, T7, T8](private val ord1: Ordering[T1], private val ord2: Ordering[T2], private val ord3: Ordering[T3], private val ord4: Ordering[T4], @@ -880,7 +880,7 @@ object Ordering extends LowPriorityOrderingImplicits { implicit def Tuple9[T1, T2, T3, T4, T5, T6, T7, T8, T9](implicit ord1: Ordering[T1], ord2: Ordering[T2], ord3: Ordering[T3], ord4: Ordering[T4], ord5: Ordering[T5], ord6: Ordering[T6], ord7: Ordering[T7], ord8 : Ordering[T8], ord9: Ordering[T9]): Ordering[(T1, T2, T3, T4, T5, T6, T7, T8, T9)] = new Tuple9Ordering(ord1, ord2, ord3, ord4, ord5, ord6, ord7, ord8, ord9) - private[this] final class Tuple9Ordering[T1, T2, T3, T4, T5, T6, T7, T8, T9](private val ord1: Ordering[T1], + private final class Tuple9Ordering[T1, T2, T3, T4, T5, T6, T7, T8, T9](private val ord1: Ordering[T1], private val ord2: Ordering[T2], private val ord3: Ordering[T3], private val ord4: Ordering[T4], diff --git a/library/src/scala/ref/PhantomReference.scala b/library/src/scala/ref/PhantomReference.scala index d2d180da1d5c..e8fddedc1e13 100644 --- a/library/src/scala/ref/PhantomReference.scala +++ b/library/src/scala/ref/PhantomReference.scala @@ -15,7 +15,7 @@ package scala.ref import scala.language.`2.13` class PhantomReference[+T <: AnyRef](value: T, queue: ReferenceQueue[T]) extends ReferenceWrapper[T] { - val underlying: java.lang.ref.PhantomReference[_ <: T] = + val underlying: java.lang.ref.PhantomReference[? <: T] = new PhantomReferenceWithWrapper[T](value, queue, this) } diff --git a/library/src/scala/ref/ReferenceQueue.scala b/library/src/scala/ref/ReferenceQueue.scala index 339d26b05ae2..827f17d43595 100644 --- a/library/src/scala/ref/ReferenceQueue.scala +++ b/library/src/scala/ref/ReferenceQueue.scala @@ -16,10 +16,10 @@ import scala.language.`2.13` class ReferenceQueue[+T <: AnyRef] { - private[ref] val underlying: java.lang.ref.ReferenceQueue[_ <: T] = new java.lang.ref.ReferenceQueue[T] + private[ref] val underlying: java.lang.ref.ReferenceQueue[? <: T] = new java.lang.ref.ReferenceQueue[T] override def toString: String = underlying.toString - protected def Wrapper(jref: java.lang.ref.Reference[_] | Null): Option[Reference[T]] = + protected def Wrapper(jref: java.lang.ref.Reference[?] | Null): Option[Reference[T]] = jref match { case null => None case ref => Some(ref.asInstanceOf[ReferenceWithWrapper[T]].wrapper) diff --git a/library/src/scala/ref/ReferenceWrapper.scala b/library/src/scala/ref/ReferenceWrapper.scala index 7877f1816016..bc877757b5df 100644 --- a/library/src/scala/ref/ReferenceWrapper.scala +++ b/library/src/scala/ref/ReferenceWrapper.scala @@ -17,7 +17,7 @@ import scala.annotation.nowarn @nowarn("cat=deprecation") trait ReferenceWrapper[+T <: AnyRef] extends Reference[T] with Proxy { - val underlying: java.lang.ref.Reference[_ <: T] + val underlying: java.lang.ref.Reference[? <: T] override def get = Option(underlying.get) def apply() = { val ret = underlying.get @@ -27,7 +27,7 @@ trait ReferenceWrapper[+T <: AnyRef] extends Reference[T] with Proxy { def clear(): Unit = underlying.clear() def enqueue(): Boolean = underlying.enqueue() def isEnqueued: Boolean = underlying.isEnqueued - def self: java.lang.ref.Reference[_ <: T] = underlying + def self: java.lang.ref.Reference[? <: T] = underlying } private trait ReferenceWithWrapper[T <: AnyRef] { diff --git a/library/src/scala/ref/SoftReference.scala b/library/src/scala/ref/SoftReference.scala index fbe505d32314..e061e80b8ff2 100644 --- a/library/src/scala/ref/SoftReference.scala +++ b/library/src/scala/ref/SoftReference.scala @@ -17,7 +17,7 @@ import scala.language.`2.13` class SoftReference[+T <: AnyRef](value : T, queue : ReferenceQueue[T] | Null) extends ReferenceWrapper[T] { def this(value : T) = this(value, null) - val underlying: java.lang.ref.SoftReference[_ <: T] = + val underlying: java.lang.ref.SoftReference[? <: T] = new SoftReferenceWithWrapper[T](value, queue, this) } diff --git a/library/src/scala/ref/WeakReference.scala b/library/src/scala/ref/WeakReference.scala index b28a1ab8d3f2..add824a1abd4 100644 --- a/library/src/scala/ref/WeakReference.scala +++ b/library/src/scala/ref/WeakReference.scala @@ -21,7 +21,7 @@ import scala.language.`2.13` */ class WeakReference[+T <: AnyRef](value: T, queue: ReferenceQueue[T] | Null) extends ReferenceWrapper[T] { def this(value: T) = this(value, null) - val underlying: java.lang.ref.WeakReference[_ <: T] = + val underlying: java.lang.ref.WeakReference[? <: T] = new WeakReferenceWithWrapper[T](value, queue, this) } diff --git a/library/src/scala/reflect/ClassManifestDeprecatedApis.scala b/library/src/scala/reflect/ClassManifestDeprecatedApis.scala index f3b866f42858..80d6c3b6b483 100644 --- a/library/src/scala/reflect/ClassManifestDeprecatedApis.scala +++ b/library/src/scala/reflect/ClassManifestDeprecatedApis.scala @@ -25,11 +25,11 @@ trait ClassManifestDeprecatedApis[T] extends OptManifest[T] { // Still in use in target test.junit.comp. @deprecated("use runtimeClass instead", "2.10.0") - def erasure: jClass[_] = runtimeClass + def erasure: jClass[?] = runtimeClass - private def subtype(sub: jClass[_], sup: jClass[_]): Boolean = { + private def subtype(sub: jClass[?], sup: jClass[?]): Boolean = { @tailrec - def loop(left: Set[jClass[_]], seen: Set[jClass[_]]): Boolean = { + def loop(left: Set[jClass[?]], seen: Set[jClass[?]]): Boolean = { left.nonEmpty && { val next = left.head val supers = next.getInterfaces.toSet ++ Option(next.getSuperclass) @@ -42,7 +42,7 @@ trait ClassManifestDeprecatedApis[T] extends OptManifest[T] { loop(Set(sub), Set()) } - private def subargs(args1: List[OptManifest[_]], args2: List[OptManifest[_]]) = (args1 corresponds args2) { + private def subargs(args1: List[OptManifest[?]], args2: List[OptManifest[?]]) = (args1 corresponds args2) { // !!! [Martin] this is wrong, need to take variance into account case (x: ClassManifest[_], y: ClassManifest[_]) => x <:< y case (x, y) => (x eq NoManifest) && (y eq NoManifest) @@ -53,11 +53,11 @@ trait ClassManifestDeprecatedApis[T] extends OptManifest[T] { * described in the header. */ @deprecated("use scala.reflect.runtime.universe.TypeTag for subtype checking instead", "2.10.0") - def <:<(that: ClassManifest[_]): Boolean = { + def <:<(that: ClassManifest[?]): Boolean = { // All types which could conform to these types will override <:<. def cannotMatch = { import Manifest._ - that.isInstanceOf[AnyValManifest[_]] || (that eq AnyVal) || (that eq Nothing) || (that eq Null) + that.isInstanceOf[AnyValManifest[?]] || (that eq AnyVal) || (that eq Nothing) || (that eq Null) } // This is wrong, and I don't know how it can be made right @@ -87,7 +87,7 @@ trait ClassManifestDeprecatedApis[T] extends OptManifest[T] { * described in the header. */ @deprecated("use scala.reflect.runtime.universe.TypeTag for subtype checking instead", "2.10.0") - def >:>(that: ClassManifest[_]): Boolean = + def >:>(that: ClassManifest[?]): Boolean = that <:< this override def canEqual(other: Any) = other match { @@ -95,7 +95,7 @@ trait ClassManifestDeprecatedApis[T] extends OptManifest[T] { case _ => false } - protected def arrayClass[A](tp: jClass[_]): jClass[Array[A]] = + protected def arrayClass[A](tp: jClass[?]): jClass[Array[A]] = java.lang.reflect.Array.newInstance(tp, 0).getClass.asInstanceOf[jClass[Array[A]]] @deprecated("use wrap instead", "2.10.0") @@ -125,15 +125,15 @@ trait ClassManifestDeprecatedApis[T] extends OptManifest[T] { @deprecated("create WrappedArray directly instead", "2.10.0") def newWrappedArray(len: Int): ArraySeq[T] = // it's safe to assume T <: AnyRef here because the method is overridden for all value type manifests - new ArraySeq.ofRef[T with AnyRef](newArray(len).asInstanceOf[Array[T with AnyRef]]).asInstanceOf[ArraySeq[T]] + new ArraySeq.ofRef[T & AnyRef](newArray(len).asInstanceOf[Array[T & AnyRef]]).asInstanceOf[ArraySeq[T]] @deprecated("use ArrayBuilder.make(this) instead", "2.10.0") def newArrayBuilder(): ArrayBuilder[T] = // it's safe to assume T <: AnyRef here because the method is overridden for all value type manifests - new ArrayBuilder.ofRef[T with AnyRef]()(this.asInstanceOf[ClassManifest[T with AnyRef]]).asInstanceOf[ArrayBuilder[T]] + new ArrayBuilder.ofRef[T & AnyRef]()(using this.asInstanceOf[ClassManifest[T & AnyRef]]).asInstanceOf[ArrayBuilder[T]] @deprecated("use scala.reflect.runtime.universe.TypeTag to capture type structure instead", "2.10.0") - def typeArguments: List[OptManifest[_]] = List() + def typeArguments: List[OptManifest[?]] = List() protected def argString = if (typeArguments.nonEmpty) typeArguments.mkString("[", ", ", "]") @@ -181,7 +181,7 @@ object ClassManifestFactory { case java.lang.Double.TYPE => Double.asInstanceOf[ClassManifest[T]] case java.lang.Boolean.TYPE => Boolean.asInstanceOf[ClassManifest[T]] case java.lang.Void.TYPE => Unit.asInstanceOf[ClassManifest[T]] - case _ => classType[T with AnyRef](clazz).asInstanceOf[ClassManifest[T]] + case _ => classType[T & AnyRef](clazz).asInstanceOf[ClassManifest[T]] } def singleType[T <: AnyRef](value: AnyRef): Manifest[T] = Manifest.singleType(value) @@ -193,27 +193,27 @@ object ClassManifestFactory { * pass varargs as arrays into this, we get an infinitely recursive call * to boxArray. (Besides, having a separate case is more efficient) */ - def classType[T](clazz: jClass[_]): ClassManifest[T] = + def classType[T](clazz: jClass[?]): ClassManifest[T] = new ClassTypeManifest[T](None, clazz, Nil) /** ClassManifest for the class type `clazz[args]`, where `clazz` is * a top-level or static class and `args` are its type arguments */ - def classType[T](clazz: jClass[_], arg1: OptManifest[_], args: OptManifest[_]*): ClassManifest[T] = + def classType[T](clazz: jClass[?], arg1: OptManifest[?], args: OptManifest[?]*): ClassManifest[T] = new ClassTypeManifest[T](None, clazz, arg1 :: args.toList) /** ClassManifest for the class type `clazz[args]`, where `clazz` is * a class with non-package prefix type `prefix` and type arguments `args`. */ - def classType[T](prefix: OptManifest[_], clazz: jClass[_], args: OptManifest[_]*): ClassManifest[T] = + def classType[T](prefix: OptManifest[?], clazz: jClass[?], args: OptManifest[?]*): ClassManifest[T] = new ClassTypeManifest[T](Some(prefix), clazz, args.toList) - def arrayType[T](arg: OptManifest[_]): ClassManifest[Array[T]] = (arg: @unchecked) match { + def arrayType[T](arg: OptManifest[?]): ClassManifest[Array[T]] = (arg: @unchecked) match { case NoManifest => Object.asInstanceOf[ClassManifest[Array[T]]] case m: ClassManifest[_] => m.asInstanceOf[ClassManifest[T]].arrayManifest } @SerialVersionUID(1L) - private class AbstractTypeClassManifest[T](prefix: OptManifest[_], name: String, clazz: jClass[_], args: OptManifest[_]*) extends ClassManifest[T] { + private class AbstractTypeClassManifest[T](prefix: OptManifest[?], name: String, clazz: jClass[?], args: OptManifest[?]*) extends ClassManifest[T] { override def runtimeClass = clazz override val typeArguments = args.toList override def toString = prefix.toString+"#"+name+argString @@ -222,7 +222,7 @@ object ClassManifestFactory { /** ClassManifest for the abstract type `prefix # name`. `upperBound` is not * strictly necessary as it could be obtained by reflection. It was * added so that erasure can be calculated without reflection. */ - def abstractType[T](prefix: OptManifest[_], name: String, clazz: jClass[_], args: OptManifest[_]*): ClassManifest[T] = + def abstractType[T](prefix: OptManifest[?], name: String, clazz: jClass[?], args: OptManifest[?]*): ClassManifest[T] = new AbstractTypeClassManifest(prefix, name, clazz) /** ClassManifest for the abstract type `prefix # name`. `upperBound` is not @@ -230,7 +230,7 @@ object ClassManifestFactory { * added so that erasure can be calculated without reflection. * todo: remove after next bootstrap */ - def abstractType[T](prefix: OptManifest[_], name: String, upperbound: ClassManifest[_], args: OptManifest[_]*): ClassManifest[T] = + def abstractType[T](prefix: OptManifest[?], name: String, upperbound: ClassManifest[?], args: OptManifest[?]*): ClassManifest[T] = new AbstractTypeClassManifest(prefix, name, upperbound.runtimeClass) } @@ -239,9 +239,9 @@ object ClassManifestFactory { @nowarn("""cat=deprecation&origin=scala\.reflect\.ClassManifest""") @SerialVersionUID(1L) private class ClassTypeManifest[T]( - prefix: Option[OptManifest[_]], - val runtimeClass: jClass[_], - override val typeArguments: List[OptManifest[_]]) extends ClassManifest[T] + prefix: Option[OptManifest[?]], + val runtimeClass: jClass[?], + override val typeArguments: List[OptManifest[?]]) extends ClassManifest[T] { override def toString = (if (prefix.isEmpty) "" else prefix.get.toString+"#") + diff --git a/library/src/scala/reflect/ClassTag.scala b/library/src/scala/reflect/ClassTag.scala index 25cf56490ff1..80ffb869c447 100644 --- a/library/src/scala/reflect/ClassTag.scala +++ b/library/src/scala/reflect/ClassTag.scala @@ -57,7 +57,7 @@ trait ClassTag[T] extends ClassManifestDeprecatedApis[T] with Equals with Serial /** A class representing the type `U` to which `T` would be erased. * Note that there is no subtyping relationship between `T` and `U`. */ - def runtimeClass: jClass[_] + def runtimeClass: jClass[?] /** Produces a `ClassTag` that knows how to instantiate an `Array[Array[T]]` */ def wrap: ClassTag[Array[T]] = ClassTag[Array[T]](arrayClass(runtimeClass)) @@ -79,11 +79,11 @@ trait ClassTag[T] extends ClassManifestDeprecatedApis[T] with Equals with Serial else None // case class accessories - override def canEqual(x: Any) = x.isInstanceOf[ClassTag[_]] - override def equals(x: Any) = x.isInstanceOf[ClassTag[_]] && this.runtimeClass == x.asInstanceOf[ClassTag[_]].runtimeClass + override def canEqual(x: Any) = x.isInstanceOf[ClassTag[?]] + override def equals(x: Any) = x.isInstanceOf[ClassTag[?]] && this.runtimeClass == x.asInstanceOf[ClassTag[?]].runtimeClass override def hashCode = runtimeClass.## override def toString = { - def prettyprint(clazz: jClass[_]): String = + def prettyprint(clazz: jClass[?]): String = if (clazz.isArray) s"Array[${prettyprint(clazz.getComponentType)}]" else clazz.getName prettyprint(runtimeClass) @@ -94,9 +94,9 @@ trait ClassTag[T] extends ClassManifestDeprecatedApis[T] with Equals with Serial * Class tags corresponding to primitive types and constructor/extractor for ClassTags. */ object ClassTag { - private[this] val ObjectTYPE = classOf[java.lang.Object] - private[this] val NothingTYPE = classOf[scala.runtime.Nothing$] - private[this] val NullTYPE = classOf[scala.runtime.Null$] + private val ObjectTYPE = classOf[java.lang.Object] + private val NothingTYPE = classOf[scala.runtime.Nothing$] + private val NullTYPE = classOf[scala.runtime.Null$] import ManifestFactory._ @@ -117,11 +117,11 @@ object ClassTag { val Null : ClassTag[scala.Null] = Manifest.Null private val cacheDisabled = java.lang.Boolean.getBoolean("scala.reflect.classtag.cache.disable") - private[this] object cache extends ClassValueCompat[jWeakReference[ClassTag[_]]] { - override def computeValue(runtimeClass: jClass[_]): jWeakReference[ClassTag[_]] = + private object cache extends ClassValueCompat[jWeakReference[ClassTag[?]]] { + override def computeValue(runtimeClass: jClass[?]): jWeakReference[ClassTag[?]] = new jWeakReference(computeTag(runtimeClass)) - def computeTag(runtimeClass: jClass[_]): ClassTag[_] = + def computeTag(runtimeClass: jClass[?]): ClassTag[?] = runtimeClass match { case x if x.isPrimitive => primitiveClassTag(runtimeClass) case ObjectTYPE => ClassTag.Object @@ -130,7 +130,7 @@ object ClassTag { case _ => new GenericClassTag[AnyRef](runtimeClass) } - private def primitiveClassTag[T](runtimeClass: Class[_]): ClassTag[_] = + private def primitiveClassTag[T](runtimeClass: Class[?]): ClassTag[?] = (runtimeClass: @unchecked) match { case java.lang.Byte.TYPE => ClassTag.Byte case java.lang.Short.TYPE => ClassTag.Short @@ -145,13 +145,13 @@ object ClassTag { } @SerialVersionUID(1L) - private class GenericClassTag[T](val runtimeClass: jClass[_]) extends ClassTag[T] { + private class GenericClassTag[T](val runtimeClass: jClass[?]) extends ClassTag[T] { override def newArray(len: Int): Array[T] = { java.lang.reflect.Array.newInstance(runtimeClass, len).asInstanceOf[Array[T]] } } - def apply[T](runtimeClass1: jClass[_]): ClassTag[T] = { + def apply[T](runtimeClass1: jClass[?]): ClassTag[T] = { if (cacheDisabled) { cache.computeTag(runtimeClass1).asInstanceOf[ClassTag[T]] } else { @@ -165,5 +165,5 @@ object ClassTag { } } - def unapply[T](ctag: ClassTag[T]): Option[Class[_]] = Some(ctag.runtimeClass) + def unapply[T](ctag: ClassTag[T]): Option[Class[?]] = Some(ctag.runtimeClass) } diff --git a/library/src/scala/reflect/Manifest.scala b/library/src/scala/reflect/Manifest.scala index 85b645633a65..d3492a2bfe5a 100644 --- a/library/src/scala/reflect/Manifest.scala +++ b/library/src/scala/reflect/Manifest.scala @@ -49,7 +49,7 @@ import scala.collection.mutable.{ArrayBuilder, ArraySeq} // TODO undeprecated until Scala reflection becomes non-experimental // @deprecated("use scala.reflect.ClassTag (to capture erasures) or scala.reflect.runtime.universe.TypeTag (to capture types) or both instead", "2.10.0") trait Manifest[T] extends ClassManifest[T] with Equals { - override def typeArguments: List[Manifest[_]] = Nil + override def typeArguments: List[Manifest[?]] = Nil override def arrayManifest: Manifest[Array[T]] = Manifest.classType[Array[T]](arrayClass[T](runtimeClass), this) @@ -80,7 +80,7 @@ object Manifest { * defined above. */ - def valueManifests: List[AnyValManifest[_]] = + def valueManifests: List[AnyValManifest[?]] = ManifestFactory.valueManifests val Byte: ManifestFactory.ByteManifest = ManifestFactory.Byte @@ -111,36 +111,36 @@ object Manifest { * pass varargs as arrays into this, we get an infinitely recursive call * to boxArray. (Besides, having a separate case is more efficient) */ - def classType[T](clazz: Predef.Class[_]): Manifest[T] = + def classType[T](clazz: Predef.Class[?]): Manifest[T] = ManifestFactory.classType[T](clazz) /** Manifest for the class type `clazz`, where `clazz` is * a top-level or static class and args are its type arguments. */ - def classType[T](clazz: Predef.Class[T], arg1: Manifest[_], args: Manifest[_]*): Manifest[T] = - ManifestFactory.classType[T](clazz, arg1, args: _*) + def classType[T](clazz: Predef.Class[T], arg1: Manifest[?], args: Manifest[?]*): Manifest[T] = + ManifestFactory.classType[T](clazz, arg1, args*) /** Manifest for the class type `clazz[args]`, where `clazz` is * a class with non-package prefix type `prefix` and type arguments `args`. */ - def classType[T](prefix: Manifest[_], clazz: Predef.Class[_], args: Manifest[_]*): Manifest[T] = - ManifestFactory.classType[T](prefix, clazz, args: _*) + def classType[T](prefix: Manifest[?], clazz: Predef.Class[?], args: Manifest[?]*): Manifest[T] = + ManifestFactory.classType[T](prefix, clazz, args*) - def arrayType[T](arg: Manifest[_]): Manifest[Array[T]] = + def arrayType[T](arg: Manifest[?]): Manifest[Array[T]] = ManifestFactory.arrayType[T](arg) /** Manifest for the abstract type `prefix # name`. `upperBound` is not * strictly necessary as it could be obtained by reflection. It was * added so that erasure can be calculated without reflection. */ - def abstractType[T](prefix: Manifest[_], name: String, upperBound: Predef.Class[_], args: Manifest[_]*): Manifest[T] = - ManifestFactory.abstractType[T](prefix, name, upperBound, args: _*) + def abstractType[T](prefix: Manifest[?], name: String, upperBound: Predef.Class[?], args: Manifest[?]*): Manifest[T] = + ManifestFactory.abstractType[T](prefix, name, upperBound, args*) /** Manifest for the unknown type `_ >: L <: U` in an existential. */ - def wildcardType[T](lowerBound: Manifest[_], upperBound: Manifest[_]): Manifest[T] = + def wildcardType[T](lowerBound: Manifest[?], upperBound: Manifest[?]): Manifest[T] = ManifestFactory.wildcardType[T](lowerBound, upperBound) /** Manifest for the intersection type `parents_0 with ... with parents_n`. */ - def intersectionType[T](parents: Manifest[_]*): Manifest[T] = - ManifestFactory.intersectionType[T](parents: _*) + def intersectionType[T](parents: Manifest[?]*): Manifest[T] = + ManifestFactory.intersectionType[T](parents*) } @@ -149,7 +149,7 @@ object Manifest { @nowarn("""cat=deprecation&origin=scala\.reflect\.ClassManifest(DeprecatedApis.*)?""") @SerialVersionUID(1L) abstract class AnyValManifest[T <: AnyVal](override val toString: String) extends Manifest[T] with Equals { - override def <:<(that: ClassManifest[_]): Boolean = + override def <:<(that: ClassManifest[?]): Boolean = (that eq this) || (that eq Manifest.Any) || (that eq Manifest.AnyVal) override def canEqual(other: Any) = other match { case _: AnyValManifest[_] => true @@ -169,7 +169,7 @@ abstract class AnyValManifest[T <: AnyVal](override val toString: String) extend */ @nowarn("""cat=deprecation&origin=scala\.reflect\.ClassManifest(DeprecatedApis.*)?""") object ManifestFactory { - def valueManifests: List[AnyValManifest[_]] = + def valueManifests: List[AnyValManifest[?]] = List(Byte, Short, Char, Int, Long, Float, Double, Boolean, Unit) @SerialVersionUID(1L) @@ -307,7 +307,7 @@ object ManifestFactory { @inline override def newArray(len: Int): Array[Unit] = new Array[Unit](len) override def newWrappedArray(len: Int): ArraySeq[Unit] = new ArraySeq.ofUnit(new Array[Unit](len)) override def newArrayBuilder(): ArrayBuilder[Unit] = new ArrayBuilder.ofUnit() - override protected def arrayClass[T](tp: Class[_]): Class[Array[T]] = + override protected def arrayClass[T](tp: Class[?]): Class[Array[T]] = if (tp eq runtimeClass) classOf[Array[scala.runtime.BoxedUnit]].asInstanceOf[Class[Array[T]]] else super.arrayClass(tp) override def unapply(x: Any): Option[Unit] = { @@ -320,14 +320,14 @@ object ManifestFactory { } val Unit: UnitManifest = new UnitManifest - private[this] val ObjectTYPE = classOf[java.lang.Object] - private[this] val NothingTYPE = classOf[scala.runtime.Nothing$] - private[this] val NullTYPE = classOf[scala.runtime.Null$] + private val ObjectTYPE = classOf[java.lang.Object] + private val NothingTYPE = classOf[scala.runtime.Nothing$] + private val NullTYPE = classOf[scala.runtime.Null$] @SerialVersionUID(1L) final private class AnyManifest extends PhantomManifest[scala.Any](ObjectTYPE, "Any") { override def newArray(len: Int) = new Array[scala.Any](len) - override def <:<(that: ClassManifest[_]): Boolean = (that eq this) + override def <:<(that: ClassManifest[?]): Boolean = (that eq this) private def readResolve(): Any = Manifest.Any } val Any: Manifest[scala.Any] = new AnyManifest @@ -335,7 +335,7 @@ object ManifestFactory { @SerialVersionUID(1L) final private class ObjectManifest extends PhantomManifest[java.lang.Object](ObjectTYPE, "Object") { override def newArray(len: Int) = new Array[java.lang.Object](len) - override def <:<(that: ClassManifest[_]): Boolean = (that eq this) || (that eq Any) + override def <:<(that: ClassManifest[?]): Boolean = (that eq this) || (that eq Any) private def readResolve(): Any = Manifest.Object } val Object: Manifest[java.lang.Object] = new ObjectManifest @@ -345,7 +345,7 @@ object ManifestFactory { @SerialVersionUID(1L) final private class AnyValPhantomManifest extends PhantomManifest[scala.AnyVal](ObjectTYPE, "AnyVal") { override def newArray(len: Int) = new Array[scala.AnyVal](len) - override def <:<(that: ClassManifest[_]): Boolean = (that eq this) || (that eq Any) + override def <:<(that: ClassManifest[?]): Boolean = (that eq this) || (that eq Any) private def readResolve(): Any = Manifest.AnyVal } val AnyVal: Manifest[scala.AnyVal] = new AnyValPhantomManifest @@ -353,7 +353,7 @@ object ManifestFactory { @SerialVersionUID(1L) final private class NullManifest extends PhantomManifest[scala.Null](NullTYPE, "Null") { override def newArray(len: Int) = new Array[scala.Null](len) - override def <:<(that: ClassManifest[_]): Boolean = + override def <:<(that: ClassManifest[?]): Boolean = (that ne null) && (that ne Nothing) && !(that <:< AnyVal) private def readResolve(): Any = Manifest.Null } @@ -362,14 +362,14 @@ object ManifestFactory { @SerialVersionUID(1L) final private class NothingManifest extends PhantomManifest[scala.Nothing](NothingTYPE, "Nothing") { override def newArray(len: Int) = new Array[scala.Nothing](len) - override def <:<(that: ClassManifest[_]): Boolean = (that ne null) + override def <:<(that: ClassManifest[?]): Boolean = (that ne null) private def readResolve(): Any = Manifest.Nothing } val Nothing: Manifest[scala.Nothing] = new NothingManifest @SerialVersionUID(1L) final private class SingletonTypeManifest[T <: AnyRef](value: AnyRef) extends Manifest[T] { - lazy val runtimeClass: Class[_ <: AnyRef] = value.getClass + lazy val runtimeClass: Class[? <: AnyRef] = value.getClass override lazy val toString = value.toString + ".type" } @@ -384,22 +384,22 @@ object ManifestFactory { * pass varargs as arrays into this, we get an infinitely recursive call * to boxArray. (Besides, having a separate case is more efficient) */ - def classType[T](clazz: Predef.Class[_]): Manifest[T] = + def classType[T](clazz: Predef.Class[?]): Manifest[T] = new ClassTypeManifest[T](None, clazz, Nil) /** Manifest for the class type `clazz`, where `clazz` is * a top-level or static class and args are its type arguments. */ - def classType[T](clazz: Predef.Class[T], arg1: Manifest[_], args: Manifest[_]*): Manifest[T] = + def classType[T](clazz: Predef.Class[T], arg1: Manifest[?], args: Manifest[?]*): Manifest[T] = new ClassTypeManifest[T](None, clazz, arg1 :: args.toList) /** Manifest for the class type `clazz[args]`, where `clazz` is * a class with non-package prefix type `prefix` and type arguments `args`. */ - def classType[T](prefix: Manifest[_], clazz: Predef.Class[_], args: Manifest[_]*): Manifest[T] = + def classType[T](prefix: Manifest[?], clazz: Predef.Class[?], args: Manifest[?]*): Manifest[T] = new ClassTypeManifest[T](Some(prefix), clazz, args.toList) @SerialVersionUID(1L) - private abstract class PhantomManifest[T](_runtimeClass: Predef.Class[_], + private abstract class PhantomManifest[T](_runtimeClass: Predef.Class[?], override val toString: String) extends ClassTypeManifest[T](None, _runtimeClass, Nil) { override def equals(that: Any): Boolean = this eq that.asInstanceOf[AnyRef] @transient @@ -409,20 +409,20 @@ object ManifestFactory { /** Manifest for the class type `clazz[args]`, where `clazz` is * a top-level or static class. */ @SerialVersionUID(1L) - private class ClassTypeManifest[T](prefix: Option[Manifest[_]], - val runtimeClass: Predef.Class[_], - override val typeArguments: List[Manifest[_]]) extends Manifest[T] { + private class ClassTypeManifest[T](prefix: Option[Manifest[?]], + val runtimeClass: Predef.Class[?], + override val typeArguments: List[Manifest[?]]) extends Manifest[T] { override def toString = (if (prefix.isEmpty) "" else prefix.get.toString+"#") + (if (runtimeClass.isArray) "Array" else runtimeClass.getName) + argString } - def arrayType[T](arg: Manifest[_]): Manifest[Array[T]] = + def arrayType[T](arg: Manifest[?]): Manifest[Array[T]] = arg.asInstanceOf[Manifest[T]].arrayManifest @SerialVersionUID(1L) - private class AbstractTypeManifest[T](prefix: Manifest[_], name: String, upperBound: Predef.Class[_], args: scala.collection.Seq[Manifest[_]]) extends Manifest[T] { + private class AbstractTypeManifest[T](prefix: Manifest[?], name: String, upperBound: Predef.Class[?], args: scala.collection.Seq[Manifest[?]]) extends Manifest[T] { def runtimeClass = upperBound override val typeArguments = args.toList override def toString = prefix.toString+"#"+name+argString @@ -431,11 +431,11 @@ object ManifestFactory { /** Manifest for the abstract type `prefix # name`. `upperBound` is not * strictly necessary as it could be obtained by reflection. It was * added so that erasure can be calculated without reflection. */ - def abstractType[T](prefix: Manifest[_], name: String, upperBound: Predef.Class[_], args: Manifest[_]*): Manifest[T] = + def abstractType[T](prefix: Manifest[?], name: String, upperBound: Predef.Class[?], args: Manifest[?]*): Manifest[T] = new AbstractTypeManifest[T](prefix, name, upperBound, args) @SerialVersionUID(1L) - private class WildcardManifest[T](lowerBound: Manifest[_], upperBound: Manifest[_]) extends Manifest[T] { + private class WildcardManifest[T](lowerBound: Manifest[?], upperBound: Manifest[?]) extends Manifest[T] { def runtimeClass = upperBound.runtimeClass override def toString = "_" + @@ -445,11 +445,11 @@ object ManifestFactory { /** Manifest for the unknown type `_ >: L <: U` in an existential. */ - def wildcardType[T](lowerBound: Manifest[_], upperBound: Manifest[_]): Manifest[T] = + def wildcardType[T](lowerBound: Manifest[?], upperBound: Manifest[?]): Manifest[T] = new WildcardManifest[T](lowerBound, upperBound) @SerialVersionUID(1L) - private class IntersectionTypeManifest[T](parents: Array[Manifest[_]]) extends Manifest[T] { + private class IntersectionTypeManifest[T](parents: Array[Manifest[?]]) extends Manifest[T] { // We use an `Array` instead of a `Seq` for `parents` to avoid cyclic dependencies during deserialization // which can cause serialization proxies to leak and cause a ClassCastException. def runtimeClass = parents(0).runtimeClass @@ -457,6 +457,6 @@ object ManifestFactory { } /** Manifest for the intersection type `parents_0 with ... with parents_n`. */ - def intersectionType[T](parents: Manifest[_]*): Manifest[T] = + def intersectionType[T](parents: Manifest[?]*): Manifest[T] = new IntersectionTypeManifest[T](parents.toArray) } diff --git a/library/src/scala/reflect/NameTransformer.scala b/library/src/scala/reflect/NameTransformer.scala index a78afcb13b6b..7d447cab0292 100644 --- a/library/src/scala/reflect/NameTransformer.scala +++ b/library/src/scala/reflect/NameTransformer.scala @@ -30,13 +30,13 @@ object NameTransformer { final val SETTER_SUFFIX_STRING = "_$eq" final val TRAIT_SETTER_SEPARATOR_STRING = "$_setter_$" - private[this] val nops = 128 - private[this] val ncodes = 26 * 26 + private val nops = 128 + private val ncodes = 26 * 26 private class OpCodes(val op: Char, val code: String, val next: OpCodes | Null) - private[this] val op2code = new Array[String | Null](nops) - private[this] val code2op = new Array[OpCodes | Null](ncodes) + private val op2code = new Array[String | Null](nops) + private val code2op = new Array[OpCodes | Null](ncodes) private def enterOp(op: Char, code: String) = { op2code(op.toInt) = code val c = (code.charAt(1) - 'a') * 26 + code.charAt(2) - 'a' @@ -73,7 +73,7 @@ object NameTransformer { val len = name.length() var i = 0 while (i < len) { - val c = name charAt i + val c = name.charAt(i) if (c < nops && (op2code(c.toInt) ne null)) { if (buf eq null) { buf = new StringBuilder() @@ -112,7 +112,7 @@ object NameTransformer { while (i < len) { var ops: OpCodes | Null = null var unicode = false - val c = name charAt i + val c = name.charAt(i) if (c == '$' && i + 2 < len) { val ch1 = name.charAt(i+1) if ('a' <= ch1 && ch1 <= 'z') { diff --git a/library/src/scala/reflect/package.scala b/library/src/scala/reflect/package.scala index 5607e883795f..c06c88d6a817 100644 --- a/library/src/scala/reflect/package.scala +++ b/library/src/scala/reflect/package.scala @@ -61,7 +61,7 @@ package object reflect { // was called before, not if the reflected object is inherently accessible. // TODO: replace by `canAccess` once we're on JDK 9+ if (!m.isAccessible: @nowarn("cat=deprecation")) { - try m setAccessible true + try m.setAccessible(true) catch { case _: SecurityException => } // does nothing } m @@ -73,9 +73,3 @@ package object reflect { // todo. once we have implicit macros for tag generation, we can remove this anchor private[scala] def materializeClassTag[T](): ClassTag[T] = macro ??? } - -/** An exception that indicates an error during Scala reflection */ -case class ScalaReflectionException(msg: String) extends Exception(msg) - -object ScalaReflectionException extends scala.runtime.AbstractFunction1[String, ScalaReflectionException]: - override def toString: String = "ScalaReflectionException" diff --git a/library/src/scala/runtime/ClassValueCompat.scala b/library/src/scala/runtime/ClassValueCompat.scala index 24daf6695013..0236d467fef1 100644 --- a/library/src/scala/runtime/ClassValueCompat.scala +++ b/library/src/scala/runtime/ClassValueCompat.scala @@ -21,27 +21,27 @@ private[scala] abstract class ClassValueCompat[T] extends ClassValueInterface[T] else new FallbackClassValue() private class JavaClassValue extends ClassValue[T] with ClassValueInterface[T] { - override def computeValue(cls: Class[_]): T = self.computeValue(cls) + override def computeValue(cls: Class[?]): T = self.computeValue(cls) } private class FallbackClassValue extends ClassValueInterface[T] { - override def get(cls: Class[_]): T = self.computeValue(cls) + override def get(cls: Class[?]): T = self.computeValue(cls) - override def remove(cls: Class[_]): Unit = {} + override def remove(cls: Class[?]): Unit = {} } - def get(cls: Class[_]): T = instance.get(cls) + def get(cls: Class[?]): T = instance.get(cls) - def remove(cls: Class[_]): Unit = instance.remove(cls) + def remove(cls: Class[?]): Unit = instance.remove(cls) - protected def computeValue(cls: Class[_]): T + protected def computeValue(cls: Class[?]): T } private[scala] object ClassValueCompat { trait ClassValueInterface[T] { - def get(cls: Class[_]): T + def get(cls: Class[?]): T - def remove(cls: Class[_]): Unit + def remove(cls: Class[?]): Unit } private val classValueAvailable: Boolean = try { diff --git a/library/src/scala/runtime/LambdaDeserialize.scala b/library/src/scala/runtime/LambdaDeserialize.scala index 202827923592..f39be095ef21 100644 --- a/library/src/scala/runtime/LambdaDeserialize.scala +++ b/library/src/scala/runtime/LambdaDeserialize.scala @@ -37,7 +37,7 @@ final class LambdaDeserialize private (lookup: MethodHandles.Lookup, targetMetho object LambdaDeserialize { @varargs @throws[Throwable] def bootstrap(lookup: MethodHandles.Lookup, invokedName: String, invokedType: MethodType, targetMethods: MethodHandle*): CallSite = { - val targetMethodsArray = targetMethods.asInstanceOf[immutable.ArraySeq[_]].unsafeArray.asInstanceOf[Array[MethodHandle]] + val targetMethodsArray = targetMethods.asInstanceOf[immutable.ArraySeq[?]].unsafeArray.asInstanceOf[Array[MethodHandle]] val exact = MethodHandleConstants.LAMBDA_DESERIALIZE_DESERIALIZE_LAMBDA.bindTo(new LambdaDeserialize(lookup, targetMethodsArray)).asType(invokedType) new ConstantCallSite(exact) } diff --git a/library/src/scala/runtime/LambdaDeserializer.scala b/library/src/scala/runtime/LambdaDeserializer.scala index 98ba8a3da983..d70982ad5a51 100644 --- a/library/src/scala/runtime/LambdaDeserializer.scala +++ b/library/src/scala/runtime/LambdaDeserializer.scala @@ -125,6 +125,6 @@ object LambdaDeserializer { } val captures = Array.tabulate(serialized.getCapturedArgCount)(n => serialized.getCapturedArg(n)) - factory.invokeWithArguments(captures: _*) + factory.invokeWithArguments(captures*) } } diff --git a/library/src/scala/runtime/LazyRef.scala b/library/src/scala/runtime/LazyRef.scala index a27f16c927a5..89246b53eda2 100644 --- a/library/src/scala/runtime/LazyRef.scala +++ b/library/src/scala/runtime/LazyRef.scala @@ -18,10 +18,10 @@ import scala.language.`2.13` @SerialVersionUID(1L) class LazyRef[T] extends Serializable { - @volatile private[this] var _initialized: Boolean = _ + @volatile private var _initialized: Boolean = compiletime.uninitialized def initialized = _initialized - private[this] var _value: T = _ + private var _value: T = compiletime.uninitialized def value: T = _value def initialize(value: T): T = { _value = value @@ -34,10 +34,10 @@ class LazyRef[T] extends Serializable { @SerialVersionUID(1L) class LazyBoolean extends Serializable { - @volatile private[this] var _initialized: Boolean = _ + @volatile private var _initialized: Boolean = compiletime.uninitialized def initialized = _initialized - private[this] var _value: Boolean = _ + private var _value: Boolean = compiletime.uninitialized def value: Boolean = _value def initialize(value: Boolean): Boolean = { _value = value @@ -50,10 +50,10 @@ class LazyBoolean extends Serializable { @SerialVersionUID(1L) class LazyByte extends Serializable { - @volatile private[this] var _initialized: Boolean = _ + @volatile private var _initialized: Boolean = compiletime.uninitialized def initialized = _initialized - private[this] var _value: Byte = _ + private var _value: Byte = compiletime.uninitialized def value: Byte = _value @@ -68,10 +68,10 @@ class LazyByte extends Serializable { @SerialVersionUID(1L) class LazyChar extends Serializable { - @volatile private[this] var _initialized: Boolean = _ + @volatile private var _initialized: Boolean = compiletime.uninitialized def initialized = _initialized - private[this] var _value: Char = _ + private var _value: Char = compiletime.uninitialized def value: Char = _value def initialize(value: Char): Char = { _value = value @@ -84,10 +84,10 @@ class LazyChar extends Serializable { @SerialVersionUID(1L) class LazyShort extends Serializable { - @volatile private[this] var _initialized: Boolean = _ + @volatile private var _initialized: Boolean = compiletime.uninitialized def initialized = _initialized - private[this] var _value: Short = _ + private var _value: Short = compiletime.uninitialized def value: Short = _value def initialize(value: Short): Short = { _value = value @@ -100,10 +100,10 @@ class LazyShort extends Serializable { @SerialVersionUID(1L) class LazyInt extends Serializable { - @volatile private[this] var _initialized: Boolean = _ + @volatile private var _initialized: Boolean = compiletime.uninitialized def initialized = _initialized - private[this] var _value: Int = _ + private var _value: Int = compiletime.uninitialized def value: Int = _value def initialize(value: Int): Int = { _value = value @@ -116,10 +116,10 @@ class LazyInt extends Serializable { @SerialVersionUID(1L) class LazyLong extends Serializable { - @volatile private[this] var _initialized: Boolean = _ + @volatile private var _initialized: Boolean = compiletime.uninitialized def initialized = _initialized - private[this] var _value: Long = _ + private var _value: Long = compiletime.uninitialized def value: Long = _value def initialize(value: Long): Long = { _value = value @@ -132,10 +132,10 @@ class LazyLong extends Serializable { @SerialVersionUID(1L) class LazyFloat extends Serializable { - @volatile private[this] var _initialized: Boolean = _ + @volatile private var _initialized: Boolean = compiletime.uninitialized def initialized = _initialized - private[this] var _value: Float = _ + private var _value: Float = compiletime.uninitialized def value: Float = _value def initialize(value: Float): Float = { _value = value @@ -148,10 +148,10 @@ class LazyFloat extends Serializable { @SerialVersionUID(1L) class LazyDouble extends Serializable { - @volatile private[this] var _initialized: Boolean = _ + @volatile private var _initialized: Boolean = compiletime.uninitialized def initialized = _initialized - private[this] var _value: Double = _ + private var _value: Double = compiletime.uninitialized def value: Double = _value def initialize(value: Double): Double = { _value = value @@ -164,7 +164,7 @@ class LazyDouble extends Serializable { @SerialVersionUID(1L) class LazyUnit extends Serializable { - @volatile private[this] var _initialized: Boolean = _ + @volatile private var _initialized: Boolean = compiletime.uninitialized def initialized = _initialized def initialize(): Unit = _initialized = true diff --git a/library/src/scala/runtime/MethodCache.scala b/library/src/scala/runtime/MethodCache.scala index d50daa770cd0..b32d4857be53 100644 --- a/library/src/scala/runtime/MethodCache.scala +++ b/library/src/scala/runtime/MethodCache.scala @@ -32,54 +32,54 @@ private[scala] sealed abstract class MethodCache { * `null` is returned. If `null` is returned, find's caller should look- * up the right method using whichever means it prefers, and add it to * the cache for later use. */ - def find(forReceiver: JClass[_]): JMethod | Null - def add(forReceiver: JClass[_], forMethod: JMethod): MethodCache + def find(forReceiver: JClass[?]): JMethod | Null + def add(forReceiver: JClass[?], forMethod: JMethod): MethodCache } private[scala] final class EmptyMethodCache extends MethodCache { - def find(forReceiver: JClass[_]): JMethod | Null = null + def find(forReceiver: JClass[?]): JMethod | Null = null - def add(forReceiver: JClass[_], forMethod: JMethod): MethodCache = + def add(forReceiver: JClass[?], forMethod: JMethod): MethodCache = new PolyMethodCache(this, forReceiver, forMethod, 1) } private[scala] final class MegaMethodCache( - private[this] val forName: String, - private[this] val forParameterTypes: Array[JClass[_]] + private val forName: String, + private val forParameterTypes: Array[JClass[?]] ) extends MethodCache { - def find(forReceiver: JClass[_]): JMethod | Null = - forReceiver.getMethod(forName, forParameterTypes:_*) + def find(forReceiver: JClass[?]): JMethod | Null = + forReceiver.getMethod(forName, forParameterTypes*) - def add(forReceiver: JClass[_], forMethod: JMethod): MethodCache = this + def add(forReceiver: JClass[?], forMethod: JMethod): MethodCache = this } private[scala] final class PolyMethodCache( - private[this] val next: MethodCache, - private[this] val receiver: JClass[_], - private[this] val method: JMethod, - private[this] val complexity: Int + private val next: MethodCache, + private val receiver: JClass[?], + private val method: JMethod, + private val complexity: Int ) extends MethodCache { /** To achieve tail recursion this must be a separate method * from `find`, because the type of next is not `PolyMethodCache`. */ - @tailrec private def findInternal(forReceiver: JClass[_]): JMethod | Null = + @tailrec private def findInternal(forReceiver: JClass[?]): JMethod | Null = if (forReceiver eq receiver) method else next match { case x: PolyMethodCache => x findInternal forReceiver case _ => next find forReceiver } - def find(forReceiver: JClass[_]): JMethod | Null = findInternal(forReceiver) + def find(forReceiver: JClass[?]): JMethod | Null = findInternal(forReceiver) // TODO: come up with a more realistic number final private val MaxComplexity = 160 - def add(forReceiver: JClass[_], forMethod: JMethod): MethodCache = + def add(forReceiver: JClass[?], forMethod: JMethod): MethodCache = if (complexity < MaxComplexity) new PolyMethodCache(this, forReceiver, forMethod, complexity + 1) else diff --git a/library/src/scala/runtime/ModuleSerializationProxy.scala b/library/src/scala/runtime/ModuleSerializationProxy.scala index 91f2d7acf1c9..e5707b30e24b 100644 --- a/library/src/scala/runtime/ModuleSerializationProxy.scala +++ b/library/src/scala/runtime/ModuleSerializationProxy.scala @@ -21,10 +21,10 @@ import scala.annotation.nowarn private[runtime] object ModuleSerializationProxy { private val instances: ClassValueCompat[Object] = new ClassValueCompat[Object] { @nowarn("cat=deprecation") // AccessController is deprecated on JDK 17 - def getModule(cls: Class[_]): Object = + def getModule(cls: Class[?]): Object = java.security.AccessController.doPrivileged( (() => cls.getField("MODULE$").get(null)): PrivilegedExceptionAction[Object]) - override protected def computeValue(cls: Class[_]): Object = + override protected def computeValue(cls: Class[?]): Object = try getModule(cls) catch { case e: PrivilegedActionException => @@ -39,6 +39,6 @@ private[runtime] object ModuleSerializationProxy { } @SerialVersionUID(1L) -final class ModuleSerializationProxy(moduleClass: Class[_]) extends Serializable { +final class ModuleSerializationProxy(moduleClass: Class[?]) extends Serializable { private def readResolve = ModuleSerializationProxy.instances.get(moduleClass) } diff --git a/library/src/scala/runtime/NonLocalReturnControl.scala b/library/src/scala/runtime/NonLocalReturnControl.scala index ad68c0162d48..4ac84221cbfc 100644 --- a/library/src/scala/runtime/NonLocalReturnControl.scala +++ b/library/src/scala/runtime/NonLocalReturnControl.scala @@ -16,7 +16,7 @@ import scala.language.`2.13` import scala.util.control.ControlThrowable // remove Unit specialization when binary compatibility permits -@annotation.nowarn("cat=lint-unit-specialization") +// @annotation.nowarn("cat=lint-unit-specialization") TODO: Add warning back when specialization is implemented class NonLocalReturnControl[@specialized(Byte, Short, Int, Long, Char, Float, Double, Boolean, Unit) T](val key: AnyRef, val value: T) extends ControlThrowable { final override def fillInStackTrace(): Throwable = this } diff --git a/library/src/scala/runtime/ScalaRunTime.scala b/library/src/scala/runtime/ScalaRunTime.scala index e288fa7ffc5e..4ccafc00cb62 100644 --- a/library/src/scala/runtime/ScalaRunTime.scala +++ b/library/src/scala/runtime/ScalaRunTime.scala @@ -31,7 +31,7 @@ object ScalaRunTime { def isArray(x: Any, atLevel: Int = 1): Boolean = x != null && isArrayClass(x.getClass, atLevel) - private def isArrayClass(clazz: jClass[_], atLevel: Int): Boolean = + private def isArrayClass(clazz: jClass[?], atLevel: Int): Boolean = clazz.isArray && (atLevel == 1 || isArrayClass(clazz.getComponentType, atLevel - 1)) // A helper method to make my life in the pattern matcher a lot easier. @@ -40,7 +40,7 @@ object ScalaRunTime { /** Return the class object representing an array with element class `clazz`. */ - def arrayClass(clazz: jClass[_]): jClass[_] = { + def arrayClass(clazz: jClass[?]): jClass[?] = { // newInstance throws an exception if the erasure is Void.TYPE. see scala/bug#5680 if (clazz == java.lang.Void.TYPE) classOf[Array[Unit]] else java.lang.reflect.Array.newInstance(clazz, 0).getClass @@ -167,8 +167,8 @@ object ScalaRunTime { /** A helper for case classes. */ def typedProductIterator[T](x: Product): Iterator[T] = { new AbstractIterator[T] { - private[this] var c: Int = 0 - private[this] val cmax = x.productArity + private var c: Int = 0 + private val cmax = x.productArity def hasNext = c < cmax def next() = { val result = x.productElement(c) @@ -196,14 +196,14 @@ object ScalaRunTime { case null => "" case p => p.getName } - def isScalaClass(x: AnyRef) = packageOf(x) startsWith "scala." - def isScalaCompilerClass(x: AnyRef) = packageOf(x) startsWith "scala.tools.nsc." + def isScalaClass(x: AnyRef) = packageOf(x).startsWith("scala.") + def isScalaCompilerClass(x: AnyRef) = packageOf(x).startsWith("scala.tools.nsc.") // includes specialized subclasses and future proofed against hypothetical TupleN (for N > 22) def isTuple(x: Any) = x != null && x.getClass.getName.startsWith("scala.Tuple") // We use reflection because the scala.xml package might not be available - def isSubClassOf(potentialSubClass: Class[_], ofClass: String) = + def isSubClassOf(potentialSubClass: Class[?], ofClass: String) = try { val classLoader = potentialSubClass.getClassLoader val clazz = Class.forName(ofClass, /*initialize =*/ false, classLoader) @@ -211,8 +211,8 @@ object ScalaRunTime { } catch { case cnfe: ClassNotFoundException => false } - def isXmlNode(potentialSubClass: Class[_]) = isSubClassOf(potentialSubClass, "scala.xml.Node") - def isXmlMetaData(potentialSubClass: Class[_]) = isSubClassOf(potentialSubClass, "scala.xml.MetaData") + def isXmlNode(potentialSubClass: Class[?]) = isSubClassOf(potentialSubClass, "scala.xml.Node") + def isXmlMetaData(potentialSubClass: Class[?]) = isSubClassOf(potentialSubClass, "scala.xml.MetaData") // When doing our own iteration is dangerous def useOwnToString(x: Any) = x match { @@ -229,7 +229,7 @@ object ScalaRunTime { // Don't want to a) traverse infinity or b) be overly helpful with peoples' custom // collections which may have useful toString methods - ticket #3710 // or c) print AbstractFiles which are somehow also Iterable[AbstractFile]s. - case x: Iterable[_] => (!x.isInstanceOf[StrictOptimizedIterableOps[_, AnyConstr, _]]) || !isScalaClass(x) || isScalaCompilerClass(x) || isXmlNode(x.getClass) || isXmlMetaData(x.getClass) + case x: Iterable[_] => (!x.isInstanceOf[StrictOptimizedIterableOps[?, AnyConstr, ?]]) || !isScalaClass(x) || isScalaCompilerClass(x) || isXmlNode(x.getClass) || isXmlMetaData(x.getClass) // Otherwise, nothing could possibly go wrong case _ => false } @@ -245,7 +245,7 @@ object ScalaRunTime { if (x.getClass.getComponentType == classOf[BoxedUnit]) (0 until min(array_length(x), maxElements)).map(_ => "()").mkString("Array(", ", ", ")") else - x.asInstanceOf[Array[_]].iterator.take(maxElements).map(inner).mkString("Array(", ", ", ")") + x.asInstanceOf[Array[?]].iterator.take(maxElements).map(inner).mkString("Array(", ", ", ")") } // The recursively applied attempt to prettify Array printing. diff --git a/library/src/scala/runtime/StructuralCallSite.scala b/library/src/scala/runtime/StructuralCallSite.scala index 26e51c518cd4..bdd6983a7dd8 100644 --- a/library/src/scala/runtime/StructuralCallSite.scala +++ b/library/src/scala/runtime/StructuralCallSite.scala @@ -20,7 +20,7 @@ import java.lang.reflect.Method final class StructuralCallSite private (callType: MethodType) { private var cache: SoftReference[MethodCache] = new SoftReference(new EmptyMethodCache) - val parameterTypes: Array[Class[_]] = callType.parameterArray + val parameterTypes: Array[Class[?]] = callType.parameterArray def get: MethodCache = { var cache = this.cache.get @@ -31,9 +31,9 @@ final class StructuralCallSite private (callType: MethodType) { cache } - def find(receiver: Class[_]): Method | Null = get.find(receiver) + def find(receiver: Class[?]): Method | Null = get.find(receiver) - def add(receiver: Class[_], m: Method): Method = { + def add(receiver: Class[?], m: Method): Method = { cache = new SoftReference(get.add(receiver, m)) m } diff --git a/library/src/scala/runtime/Tuple2Zipped.scala b/library/src/scala/runtime/Tuple2Zipped.scala index 0c4e9efaef48..a32dc9f960e0 100644 --- a/library/src/scala/runtime/Tuple2Zipped.scala +++ b/library/src/scala/runtime/Tuple2Zipped.scala @@ -137,8 +137,8 @@ object Tuple2Zipped { @deprecated("Use xs.lazyZip(ys)", since = "2.13.0") def zipped[El1, It1 <: Iterable[El1], El2, It2 <: Iterable[El2]] - (implicit w1: T1 => IterableOps[El1, Iterable, It1] with It1, - w2: T2 => IterableOps[El2, Iterable, It2] with It2 + (implicit w1: T1 => IterableOps[El1, Iterable, It1] & It1, + w2: T2 => IterableOps[El2, Iterable, It2] & It2 ): Tuple2Zipped[El1, It1, El2, It2] = new Tuple2Zipped((w1(x._1), w2(x._2))) } } diff --git a/library/src/scala/runtime/Tuple3Zipped.scala b/library/src/scala/runtime/Tuple3Zipped.scala index cb164512daa5..84d07fe61340 100644 --- a/library/src/scala/runtime/Tuple3Zipped.scala +++ b/library/src/scala/runtime/Tuple3Zipped.scala @@ -148,9 +148,9 @@ object Tuple3Zipped { @deprecated("Use xs.lazyZip(ys).lazyZip(zs)", since = "2.13.0") def zipped[El1, It1 <: Iterable[El1], El2, It2 <: Iterable[El2], El3, It3 <: Iterable[El3]] - (implicit w1: T1 => IterableOps[El1, Iterable, It1] with It1, - w2: T2 => IterableOps[El2, Iterable, It2] with It2, - w3: T3 => IterableOps[El3, Iterable, It3] with It3 + (implicit w1: T1 => IterableOps[El1, Iterable, It1] & It1, + w2: T2 => IterableOps[El2, Iterable, It2] & It2, + w3: T3 => IterableOps[El3, Iterable, It3] & It3 ): Tuple3Zipped[El1, It1, El2, It2, El3, It3] = new Tuple3Zipped((w1(x._1), w2(x._2), w3(x._3))) } } diff --git a/library/src/scala/sys/ShutdownHookThread.scala b/library/src/scala/sys/ShutdownHookThread.scala index d9499d5e1ad1..ea213079820d 100644 --- a/library/src/scala/sys/ShutdownHookThread.scala +++ b/library/src/scala/sys/ShutdownHookThread.scala @@ -19,11 +19,11 @@ import scala.language.`2.13` * how to unregister itself. */ class ShutdownHookThread private (runnable: Runnable, name: String) extends Thread(runnable, name) { - def remove() = Runtime.getRuntime removeShutdownHook this + def remove() = Runtime.getRuntime.removeShutdownHook(this) } object ShutdownHookThread { - private[this] var hookNameCount: Int = 0 + private var hookNameCount: Int = 0 private def hookName(): String = synchronized { hookNameCount += 1 "shutdownHook" + hookNameCount @@ -33,7 +33,7 @@ object ShutdownHookThread { */ def apply(body: => Unit): ShutdownHookThread = { val t = new ShutdownHookThread(() => body, hookName()) - Runtime.getRuntime addShutdownHook t + Runtime.getRuntime.addShutdownHook(t) t } } diff --git a/library/src/scala/sys/SystemProperties.scala b/library/src/scala/sys/SystemProperties.scala index 31d7ea3edc55..2c28be05ba86 100644 --- a/library/src/scala/sys/SystemProperties.scala +++ b/library/src/scala/sys/SystemProperties.scala @@ -36,7 +36,7 @@ extends mutable.AbstractMap[String, String | Null] { def iterator: Iterator[(String, String)] = wrapAccess { val ps = System.getProperties() - names map (k => (k, ps getProperty k)) filter (_._2 ne null) + names map (k => (k, ps.getProperty(k))) filter (_._2 ne null) } getOrElse Iterator.empty override def isEmpty: Boolean = iterator.isEmpty @@ -68,7 +68,8 @@ object SystemProperties { /** An unenforceable, advisory only place to do some synchronization when * mutating system properties. */ - def exclusively[T](body: => T): T = this synchronized body + def exclusively[T](body: => T): T = this.synchronized: + body implicit def systemPropertiesToCompanion(p: SystemProperties): SystemProperties.type = this diff --git a/library/src/scala/sys/process/BasicIO.scala b/library/src/scala/sys/process/BasicIO.scala index 3a2b99b58c5c..d3274027c73d 100644 --- a/library/src/scala/sys/process/BasicIO.scala +++ b/library/src/scala/sys/process/BasicIO.scala @@ -55,7 +55,7 @@ object BasicIO { case Right(s) => Some((s, q)) } } - new LazilyListed((s: T) => queue put Right(s), code => queue put Left(code), ll) + new LazilyListed((s: T) => queue.put(Right(s)), code => queue.put(Left(code)), ll) } } @@ -75,7 +75,7 @@ object BasicIO { case Left(code) => if (nonzeroException) scala.sys.error("Nonzero exit code: " + code) else Stream.empty case Right(s) => Stream.cons(s, next()) } - new Streamed((s: T) => q put Right(s), code => q put Left(code), () => next()) + new Streamed((s: T) => q.put(Right(s)), code => q.put(Left(code)), () => next()) } } @@ -253,12 +253,12 @@ object BasicIO { try transferFullyImpl(in, out) catch onIOInterrupt(()) - private[this] def appendLine(buffer: Appendable): String => Unit = line => { - buffer append line - buffer append Newline + private def appendLine(buffer: Appendable): String => Unit = line => { + buffer.append(line) + buffer.append(Newline) } - private[this] def transferFullyImpl(in: InputStream, out: OutputStream): Unit = { + private def transferFullyImpl(in: InputStream, out: OutputStream): Unit = { val buffer = new Array[Byte](BufferSize) @tailrec def loop(): Unit = { val byteCount = in.read(buffer) diff --git a/library/src/scala/sys/process/Process.scala b/library/src/scala/sys/process/Process.scala index be9a3490ebe4..14035dbb3dcc 100644 --- a/library/src/scala/sys/process/Process.scala +++ b/library/src/scala/sys/process/Process.scala @@ -77,7 +77,7 @@ trait ProcessCreation { * @example {{{ apply("java", new java.io.File("/opt/app"), "CLASSPATH" -> "library.jar") }}} */ def apply(command: String, cwd: File, extraEnv: (String, String)*): ProcessBuilder = - apply(command, Some(cwd), extraEnv: _*) + apply(command, Some(cwd), extraEnv*) /** Creates a [[scala.sys.process.ProcessBuilder]] with working dir set to `File` and extra * environment variables. @@ -85,7 +85,7 @@ trait ProcessCreation { * @example {{{ apply("java" :: javaArgs, new java.io.File("/opt/app"), "CLASSPATH" -> "library.jar") }}} */ def apply(command: scala.collection.Seq[String], cwd: File, extraEnv: (String, String)*): ProcessBuilder = - apply(command, Some(cwd), extraEnv: _*) + apply(command, Some(cwd), extraEnv*) /** Creates a [[scala.sys.process.ProcessBuilder]] with working dir optionally set to * `File` and extra environment variables. @@ -93,7 +93,7 @@ trait ProcessCreation { * @example {{{ apply("java", params.get("cwd"), "CLASSPATH" -> "library.jar") }}} */ def apply(command: String, cwd: Option[File], extraEnv: (String, String)*): ProcessBuilder = - apply(Parser.tokenize(command), cwd, extraEnv: _*) + apply(Parser.tokenize(command), cwd, extraEnv*) /** Creates a [[scala.sys.process.ProcessBuilder]] with working dir optionally set to * `File` and extra environment variables. @@ -101,8 +101,8 @@ trait ProcessCreation { * @example {{{ apply("java" :: javaArgs, params.get("cwd"), "CLASSPATH" -> "library.jar") }}} */ def apply(command: scala.collection.Seq[String], cwd: Option[File], extraEnv: (String, String)*): ProcessBuilder = { - val jpb = new JProcessBuilder(command.toArray: _*) - cwd foreach (jpb directory _) + val jpb = new JProcessBuilder(command.toArray*) + cwd foreach (jpb.directory(_)) extraEnv foreach { case (k, v) => jpb.environment.put(k, v) } apply(jpb) } diff --git a/library/src/scala/sys/process/ProcessBuilderImpl.scala b/library/src/scala/sys/process/ProcessBuilderImpl.scala index 7dd74c67bbec..02857c067cf3 100644 --- a/library/src/scala/sys/process/ProcessBuilderImpl.scala +++ b/library/src/scala/sys/process/ProcessBuilderImpl.scala @@ -104,7 +104,7 @@ private[process] trait ProcessBuilderImpl { protected def toSource: AbstractBuilder = this protected def toSink: AbstractBuilder = this - private[this] val defaultStreamCapacity = 4096 + private val defaultStreamCapacity = 4096 def #|(other: ProcessBuilder): ProcessBuilder = { require(other.canPipeTo, "Piping to multiple processes is not supported.") @@ -157,7 +157,7 @@ private[process] trait ProcessBuilderImpl { */ def daemonized(): ProcessBuilder = new DaemonBuilder(this) - private[this] def slurp(log: Option[ProcessLogger], withIn: Boolean): String = { + private def slurp(log: Option[ProcessLogger], withIn: Boolean): String = { val buffer = new StringBuffer val code = this ! BasicIO(withIn, buffer, log) @@ -165,7 +165,7 @@ private[process] trait ProcessBuilderImpl { else scala.sys.error("Nonzero exit value: " + code) } - private[this] def lazyLines( + private def lazyLines( withInput: Boolean, nonZeroException: Boolean, log: Option[ProcessLogger], @@ -189,7 +189,7 @@ private[process] trait ProcessBuilderImpl { } @deprecated("internal", since = "2.13.4") - private[this] def lineStream( + private def lineStream( withInput: Boolean, nonZeroException: Boolean, log: Option[ProcessLogger], @@ -202,7 +202,7 @@ private[process] trait ProcessBuilderImpl { streamed.stream() } - private[this] def runBuffered(log: ProcessLogger, connectInput: Boolean) = + private def runBuffered(log: ProcessLogger, connectInput: Boolean) = log buffer run(log, connectInput).exitValue() def canPipeTo = false @@ -223,13 +223,13 @@ private[process] trait ProcessBuilderImpl { } private[process] abstract class BasicBuilder extends AbstractBuilder { - protected[this] def checkNotThis(a: ProcessBuilder) = require(a != this, "Compound process '" + a + "' cannot contain itself.") + protected def checkNotThis(a: ProcessBuilder) = require(a != this, "Compound process '" + a + "' cannot contain itself.") final def run(io: ProcessIO): Process = { val p = createProcess(io) p.start() p } - protected[this] def createProcess(io: ProcessIO): BasicProcess + protected def createProcess(io: ProcessIO): BasicProcess } private[process] abstract class SequentialBuilder( diff --git a/library/src/scala/sys/process/ProcessImpl.scala b/library/src/scala/sys/process/ProcessImpl.scala index c120b6607a69..bd8cb792ec96 100644 --- a/library/src/scala/sys/process/ProcessImpl.scala +++ b/library/src/scala/sys/process/ProcessImpl.scala @@ -75,7 +75,7 @@ private[process] trait ProcessImpl { evaluateSecondProcess: Int => Boolean ) extends CompoundProcess { - protected[this] override def runAndExitValue() = { + protected override def runAndExitValue() = { val first = a.run(io) runInterruptible(first.exitValue())(first.destroy()) flatMap { codeA => if (evaluateSecondProcess(codeA)) { @@ -121,9 +121,9 @@ private[process] trait ProcessImpl { } /** Start and block until the exit value is available and then return it in Some. Return None if destroyed (use 'run')*/ - protected[this] def runAndExitValue(): Option[Int] + protected def runAndExitValue(): Option[Int] - protected[this] def runInterruptible[T](action: => T)(destroyImpl: => Unit): Option[T] = { + protected def runInterruptible[T](action: => T)(destroyImpl: => Unit): Option[T] = { try Some(action) catch onInterrupt { destroyImpl; None } } @@ -132,8 +132,8 @@ private[process] trait ProcessImpl { private[process] class PipedProcesses(a: ProcessBuilder, b: ProcessBuilder, defaultIO: ProcessIO, toError: Boolean) extends CompoundProcess { protected def newSource: PipeSource = new PipeSource(a.toString) protected def newSink: PipeSink = new PipeSink(b.toString) - protected[this] override def runAndExitValue() = runAndExitValue(newSource, newSink) - protected[this] def runAndExitValue(source: PipeSource, sink: PipeSink): Option[Int] = { + protected override def runAndExitValue() = runAndExitValue(newSource, newSink) + protected def runAndExitValue(source: PipeSource, sink: PipeSink): Option[Int] = { source connectOut sink source.start() sink.start() @@ -195,8 +195,8 @@ private[process] trait ProcessImpl { private[process] class PipeSource(label: => String) extends PipeThread(isSink = false, () => label) { setName(s"PipeSource($label)-$getName") - protected[this] val pipe = new PipedOutputStream - protected[this] val source = new LinkedBlockingQueue[Option[InputStream]](1) + protected val pipe = new PipedOutputStream + protected val source = new LinkedBlockingQueue[Option[InputStream]](1) override final def run(): Unit = { @tailrec def go(): Unit = source.take() match { @@ -218,8 +218,8 @@ private[process] trait ProcessImpl { } private[process] class PipeSink(label: => String) extends PipeThread(isSink = true, () => label) { setName(s"PipeSink($label)-$getName") - protected[this] val pipe = new PipedInputStream - protected[this] val sink = new LinkedBlockingQueue[Option[OutputStream]](1) + protected val pipe = new PipedInputStream + protected val sink = new LinkedBlockingQueue[Option[OutputStream]](1) override def run(): Unit = { @tailrec def go(): Unit = sink.take() match { @@ -231,7 +231,7 @@ private[process] trait ProcessImpl { finally BasicIO close pipe } def connectOut(out: OutputStream): Unit = sink.put(Some(out)) - def connectIn(pipeOut: PipedOutputStream): Unit = pipe connect pipeOut + def connectIn(pipeOut: PipedOutputStream): Unit = pipe.connect(pipeOut) def release(): Unit = { interrupt() done() @@ -244,7 +244,7 @@ private[process] trait ProcessImpl { * The implementation of `exitValue` waits until these threads die before returning. */ private[process] class DummyProcess(action: => Int) extends Process { - private[this] val (thread, value) = Future(action) + private val (thread, value) = Future(action) override def isAlive() = thread.isAlive() override def exitValue() = value() override def destroy(): Unit = { } @@ -278,7 +278,7 @@ private[process] trait ProcessImpl { finally interrupt() } // we interrupt the input thread to notify it that it can terminate - private[this] def interrupt(): Unit = if (inputThread != null) inputThread.interrupt() + private def interrupt(): Unit = if (inputThread != null) inputThread.interrupt() } private[process] final class ThreadProcess(thread: Thread, success: LinkedBlockingQueue[Boolean]) extends Process { override def isAlive() = thread.isAlive() diff --git a/library/src/scala/sys/process/ProcessLogger.scala b/library/src/scala/sys/process/ProcessLogger.scala index 621451cb619c..8676b9ea9d5b 100644 --- a/library/src/scala/sys/process/ProcessLogger.scala +++ b/library/src/scala/sys/process/ProcessLogger.scala @@ -61,7 +61,7 @@ trait ProcessLogger { /** A [[scala.sys.process.ProcessLogger]] that writes output to a file. */ class FileProcessLogger(file: File) extends ProcessLogger with Closeable with Flushable { - private[this] val writer = ( + private val writer = ( new PrintWriter( new BufferedWriter( new OutputStreamWriter( @@ -70,8 +70,8 @@ class FileProcessLogger(file: File) extends ProcessLogger with Closeable with Fl ) ) ) - def out(s: => String): Unit = writer println s - def err(s: => String): Unit = writer println s + def out(s: => String): Unit = writer.println(s) + def err(s: => String): Unit = writer.println(s) def buffer[T](f: => T): T = f def close(): Unit = writer.close() def flush(): Unit = writer.flush() diff --git a/library/src/scala/util/DynamicVariable.scala b/library/src/scala/util/DynamicVariable.scala index 1f05de8ab5ca..afe61cfb73ff 100644 --- a/library/src/scala/util/DynamicVariable.scala +++ b/library/src/scala/util/DynamicVariable.scala @@ -40,8 +40,8 @@ import java.lang.InheritableThreadLocal * are independent of those for the original thread. */ class DynamicVariable[T](init: T) { - private[this] val tl = new InheritableThreadLocal[T] { - override def initialValue: T with AnyRef = init.asInstanceOf[T with AnyRef] + private val tl = new InheritableThreadLocal[T] { + override def initialValue: T & AnyRef = init.asInstanceOf[T & AnyRef] } /** Retrieve the current value */ @@ -55,16 +55,16 @@ class DynamicVariable[T](init: T) { */ def withValue[S](newval: T)(thunk: => S): S = { val oldval = value - tl set newval + tl.set(newval) try thunk - finally tl set oldval + finally tl.set(oldval) } /** Change the currently bound value, discarding the old value. * Usually withValue() gives better semantics. */ - def value_=(newval: T) = tl set newval + def value_=(newval: T) = tl.set(newval) override def toString: String = "DynamicVariable(" + value + ")" } diff --git a/library/src/scala/util/Properties.scala b/library/src/scala/util/Properties.scala index 2bc065d5cddf..765d5d17e5dc 100644 --- a/library/src/scala/util/Properties.scala +++ b/library/src/scala/util/Properties.scala @@ -21,7 +21,7 @@ import scala.annotation.tailrec /** Loads `library.properties` from the jar. */ object Properties extends PropertiesTrait { protected def propCategory = "library" - protected def pickJarBasedOn: Class[Option[_]] = classOf[Option[_]] + protected def pickJarBasedOn: Class[Option[?]] = classOf[Option[?]] /** Scala manifest attributes. */ @@ -30,7 +30,7 @@ object Properties extends PropertiesTrait { private[scala] trait PropertiesTrait { protected def propCategory: String // specializes the remainder of the values - protected def pickJarBasedOn: Class[_] // props file comes from jar containing this + protected def pickJarBasedOn: Class[?] // props file comes from jar containing this /** The name of the properties file */ protected val propFilename = "/" + propCategory + ".properties" @@ -38,9 +38,9 @@ private[scala] trait PropertiesTrait { /** The loaded properties */ protected lazy val scalaProps: java.util.Properties = { val props = new java.util.Properties - val stream = pickJarBasedOn getResourceAsStream propFilename + val stream = pickJarBasedOn.getResourceAsStream(propFilename) if (stream ne null) - quietlyDispose(props load stream, stream.close) + quietlyDispose(props.load(stream), stream.close) props } @@ -62,8 +62,8 @@ private[scala] trait PropertiesTrait { def setProp(name: String, value: String): String = System.setProperty(name, value) def clearProp(name: String): String = System.clearProperty(name) - def envOrElse(name: String, alt: => String): String = Option(System getenv name) getOrElse alt - def envOrNone(name: String): Option[String] = Option(System getenv name) + def envOrElse(name: String, alt: => String): String = Option(System.getenv(name)) getOrElse alt + def envOrNone(name: String): Option[String] = Option(System.getenv(name)) def envOrSome(name: String, alt: => Option[String]) = envOrNone(name) orElse alt @@ -228,6 +228,6 @@ private[scala] trait PropertiesTrait { // provide a main method so version info can be obtained by running this def main(args: Array[String]): Unit = { val writer = new PrintWriter(Console.err, true) - writer println versionMsg + writer.println(versionMsg) } } diff --git a/library/src/scala/util/Random.scala b/library/src/scala/util/Random.scala index e79bd2f5dfcc..f7c04c6646f1 100644 --- a/library/src/scala/util/Random.scala +++ b/library/src/scala/util/Random.scala @@ -247,7 +247,7 @@ class Random(val self: java.util.Random) extends AnyRef with Serializable { def alphanumeric: LazyList[Char] = { def nextAlphaNum: Char = { val chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" - chars charAt (self nextInt chars.length) + chars.charAt(self.nextInt(chars.length)) } LazyList continually nextAlphaNum diff --git a/library/src/scala/util/Using.scala b/library/src/scala/util/Using.scala index d0c6bdbde4fa..dd3333cf0c76 100644 --- a/library/src/scala/util/Using.scala +++ b/library/src/scala/util/Using.scala @@ -178,7 +178,7 @@ object Using { import Manager._ private var closed = false - private[this] var resources: List[Resource[_]] = Nil + private var resources: List[Resource[?]] = Nil /** Registers the specified resource with this manager, so that * the resource is released when the manager is closed, and then @@ -209,7 +209,7 @@ object Using { } finally { closed = true var rs = resources - resources = nullForGC[List[Resource[_]]] // allow GC, in case something is holding a reference to `this` + resources = nullForGC[List[Resource[?]]] // allow GC, in case something is holding a reference to `this` while (rs != null && rs.nonEmpty) { val resource = rs.head rs = rs.tail diff --git a/library/src/scala/util/control/Breaks.scala b/library/src/scala/util/control/Breaks.scala index 601447e5d099..1ae70e5270e7 100644 --- a/library/src/scala/util/control/Breaks.scala +++ b/library/src/scala/util/control/Breaks.scala @@ -69,7 +69,7 @@ import scala.language.`2.13` */ class Breaks { - private[this] val breakException = new BreakControl + private val breakException = new BreakControl /** A block from which one can exit with a `break`. The `break` may be * executed further down in the call stack provided that it is called on the diff --git a/library/src/scala/util/control/Exception.scala b/library/src/scala/util/control/Exception.scala index 76861c23e853..4bbe41b11594 100644 --- a/library/src/scala/util/control/Exception.scala +++ b/library/src/scala/util/control/Exception.scala @@ -181,7 +181,7 @@ object Exception { trait Described { protected val name: String - private[this] var _desc: String = "" + private var _desc: String = "" def desc: String = _desc def withDesc(s: String): this.type = { _desc = s @@ -301,8 +301,8 @@ object Exception { * to catch exactly what you specify, use `catchingPromiscuously` instead. * @group composition-catch */ - def catching[T](exceptions: Class[_]*): Catch[T] = - new Catch(pfFromExceptions(exceptions : _*)) withDesc (exceptions map (_.getName) mkString ", ") + def catching[T](exceptions: Class[?]*): Catch[T] = + new Catch(pfFromExceptions(exceptions*)) withDesc (exceptions map (_.getName) mkString ", ") def catching[T](c: Catcher[T]): Catch[T] = new Catch(c) @@ -311,26 +311,26 @@ object Exception { * catch whatever you ask of it including $protectedExceptions. * @group composition-catch-promiscuously */ - def catchingPromiscuously[T](exceptions: Class[_]*): Catch[T] = catchingPromiscuously(pfFromExceptions(exceptions : _*)) + def catchingPromiscuously[T](exceptions: Class[?]*): Catch[T] = catchingPromiscuously(pfFromExceptions(exceptions*)) def catchingPromiscuously[T](c: Catcher[T]): Catch[T] = new Catch(c, None, _ => false) /** Creates a `Catch` object which catches and ignores any of the supplied exceptions. * @group composition-catch */ - def ignoring(exceptions: Class[_]*): Catch[Unit] = - catching(exceptions: _*) withApply (_ => ()) + def ignoring(exceptions: Class[?]*): Catch[Unit] = + catching(exceptions*) withApply (_ => ()) /** Creates a `Catch` object which maps all the supplied exceptions to `None`. * @group composition-catch */ - def failing[T](exceptions: Class[_]*): Catch[Option[T]] = - catching(exceptions: _*) withApply (_ => None) + def failing[T](exceptions: Class[?]*): Catch[Option[T]] = + catching(exceptions*) withApply (_ => None) /** Creates a `Catch` object which maps all the supplied exceptions to the given value. * @group composition-catch */ - def failAsValue[T](exceptions: Class[_]*)(value: => T): Catch[T] = - catching(exceptions: _*) withApply (_ => value) + def failAsValue[T](exceptions: Class[?]*)(value: => T): Catch[T] = + catching(exceptions*) withApply (_ => value) class By[T,R](f: T => R) { def by(x: T): R = f(x) @@ -344,8 +344,8 @@ object Exception { * }}} * @group dsl */ - def handling[T](exceptions: Class[_]*): By[Throwable => T, Catch[T]] = { - def fun(f: Throwable => T): Catch[T] = catching(exceptions: _*) withApply f + def handling[T](exceptions: Class[?]*): By[Throwable => T, Catch[T]] = { + def fun(f: Throwable => T): Catch[T] = catching(exceptions*) withApply f new By[Throwable => T, Catch[T]](fun) } @@ -357,19 +357,19 @@ object Exception { /** Creates a `Catch` object which unwraps any of the supplied exceptions. * @group composition-catch */ - def unwrapping[T](exceptions: Class[_]*): Catch[T] = { + def unwrapping[T](exceptions: Class[?]*): Catch[T] = { @tailrec def unwrap(x: Throwable): Throwable = if (wouldMatch(x, exceptions) && x.getCause != null) unwrap(x.getCause) else x - catching(exceptions: _*) withApply (x => throw unwrap(x)) + catching(exceptions*) withApply (x => throw unwrap(x)) } /** Private **/ - private def wouldMatch(x: Throwable, classes: scala.collection.Seq[Class[_]]): Boolean = - classes exists (_ isAssignableFrom x.getClass) + private def wouldMatch(x: Throwable, classes: scala.collection.Seq[Class[?]]): Boolean = + classes exists (_.isAssignableFrom(x.getClass)) - private def pfFromExceptions(exceptions: Class[_]*): PartialFunction[Throwable, Nothing] = + private def pfFromExceptions(exceptions: Class[?]*): PartialFunction[Throwable, Nothing] = { case x if wouldMatch(x, exceptions) => throw x } } diff --git a/library/src/scala/util/control/NoStackTrace.scala b/library/src/scala/util/control/NoStackTrace.scala index 59d53e02780c..b24b3a46f3a3 100644 --- a/library/src/scala/util/control/NoStackTrace.scala +++ b/library/src/scala/util/control/NoStackTrace.scala @@ -32,6 +32,6 @@ object NoStackTrace { final def noSuppression = _noSuppression // two-stage init to make checkinit happy, since sys.SystemProperties.noTraceSuppression.value calls back into NoStackTrace.noSuppression - final private[this] var _noSuppression = false + final private var _noSuppression = false _noSuppression = System.getProperty("scala.control.noTraceSuppression", "").equalsIgnoreCase("true") } diff --git a/library/src/scala/util/hashing/MurmurHash3.scala b/library/src/scala/util/hashing/MurmurHash3.scala index a65a0e2c2771..ab1f866a263c 100644 --- a/library/src/scala/util/hashing/MurmurHash3.scala +++ b/library/src/scala/util/hashing/MurmurHash3.scala @@ -291,7 +291,7 @@ private[hashing] class MurmurHash3 { /** Compute the hash of a List. Potential range hashes are recognized to produce a * hash that is compatible with rangeHash. */ - final def listHash(xs: scala.collection.immutable.List[_], seed: Int): Int = { + final def listHash(xs: scala.collection.immutable.List[?], seed: Int): Int = { var n = 0 var h = seed var rangeState = 0 // 0 = no data, 1 = first elem read, 2 = has valid diff, 3 = invalid @@ -402,13 +402,13 @@ object MurmurHash3 extends MurmurHash3 { /** To offer some potential for optimization. */ - def seqHash(xs: scala.collection.Seq[_]): Int = xs match { + def seqHash(xs: scala.collection.Seq[?]): Int = xs match { case xs: scala.collection.IndexedSeq[_] => indexedSeqHash(xs, seqSeed) case xs: List[_] => listHash(xs, seqSeed) case xs => orderedHash(xs, seqSeed) } - def mapHash(xs: scala.collection.Map[_, _]): Int = { + def mapHash(xs: scala.collection.Map[?, ?]): Int = { if (xs.isEmpty) emptyMapHash else { class accum extends Function2[Any, Any, Unit] { @@ -433,7 +433,7 @@ object MurmurHash3 extends MurmurHash3 { } private[scala] val emptyMapHash = unorderedHash(Nil, mapSeed) - def setHash(xs: scala.collection.Set[_]): Int = unorderedHash(xs, setSeed) + def setHash(xs: scala.collection.Set[?]): Int = unorderedHash(xs, setSeed) class ArrayHashing[@specialized T] extends Hashing[Array[T]] { def hash(a: Array[T]) = arrayHash(a) diff --git a/library/src/scala/util/matching/Regex.scala b/library/src/scala/util/matching/Regex.scala index 826d2ad9b604..f81d37d89e55 100644 --- a/library/src/scala/util/matching/Regex.scala +++ b/library/src/scala/util/matching/Regex.scala @@ -232,7 +232,7 @@ class Regex private[matching](val pattern: Pattern, groupNames: String*) extends */ // we cannot add the alternative `def this(regex: String)` in a forward binary compatible way: // @deprecated("use inline group names like (?X) instead", "2.13.7") - def this(regex: String, groupNames: String*) = this(Pattern.compile(regex), groupNames: _*) + def this(regex: String, groupNames: String*) = this(Pattern.compile(regex), groupNames*) /** Tries to match a [[java.lang.CharSequence]]. * @@ -323,9 +323,9 @@ class Regex private[matching](val pattern: Pattern, groupNames: String*) extends * @return The match */ def unapplySeq(c: Char): Option[List[Char]] = { - val m = pattern matcher c.toString + val m = pattern.matcher(c.toString) if (runMatcher(m)) { - if (m.groupCount > 0) Some((m group 1).toList) else Some(Nil) + if (m.groupCount > 0) Some((m.group(1)).toList) else Some(Nil) } else None } @@ -590,7 +590,7 @@ class Regex private[matching](val pattern: Pattern, groupNames: String*) extends * * @return The new unanchored regex */ - def unanchored: UnanchoredRegex = new Regex(pattern, groupNames: _*) with UnanchoredRegex { override def anchored = outer } + def unanchored: UnanchoredRegex = new Regex(pattern, groupNames*) with UnanchoredRegex { override def anchored = outer } def anchored: Regex = this def regex: String = pattern.pattern @@ -695,7 +695,7 @@ object Regex { @scala.annotation.nowarn("msg=deprecated") private def groupNamesNowarn: Seq[String] = groupNames - private[this] lazy val nameToIndex: Map[String, Int] = + private lazy val nameToIndex: Map[String, Int] = Map[String, Int]() ++ ("" :: groupNamesNowarn.toList).zipWithIndex /** Returns the group with the given name. @@ -710,11 +710,11 @@ object Regex { */ def group(id: String): String | Null = ( if (groupNamesNowarn.isEmpty) - matcher group id + matcher.group(id) else nameToIndex.get(id) match { case Some(index) => group(index) - case None => matcher group id + case None => matcher.group(id) } ) @@ -739,9 +739,9 @@ object Regex { /** The number of subgroups. */ def groupCount: Int = matcher.groupCount - private[this] lazy val starts: Array[Int] = + private lazy val starts: Array[Int] = Array.tabulate(groupCount + 1) { matcher.start } - private[this] lazy val ends: Array[Int] = + private lazy val ends: Array[Int] = Array.tabulate(groupCount + 1) { matcher.end } /** The index of the first matched character in group `i`. */ @@ -812,7 +812,7 @@ object Regex { protected[Regex] val matcher = regex.pattern.matcher(source) // 0 = not yet matched, 1 = matched, 2 = advanced to match, 3 = no more matches - private[this] var nextSeen = 0 + private var nextSeen = 0 /** Return true if `next` will find a match. * As a side effect, advance the underlying matcher if necessary; @@ -845,7 +845,7 @@ object Regex { override def toString: String = super[AbstractIterator].toString // ensure we're at a match - private[this] def ensure(): Unit = nextSeen match { + private def ensure(): Unit = nextSeen match { case 0 => if (!hasNext) throw new IllegalStateException case 1 => () case 2 => () @@ -886,7 +886,7 @@ object Regex { private[matching] trait Replacement { protected def matcher: Matcher - private[this] val sb = new java.lang.StringBuffer // StringBuffer for JDK 8 compatibility + private val sb = new java.lang.StringBuffer // StringBuffer for JDK 8 compatibility // Appends the remaining input and returns the result text. def replaced = { @@ -904,7 +904,7 @@ object Regex { * * @example {{{List("US\$", "CAN\$").map(Regex.quote).mkString("|").r}}} */ - def quote(text: String): String = Pattern quote text + def quote(text: String): String = Pattern.quote(text) /** Quotes replacement strings to be used in replacement methods. * @@ -918,5 +918,5 @@ object Regex { * @return A string that can be used to replace matches with `text`. * @example {{{"CURRENCY".r.replaceAllIn(input, Regex quoteReplacement "US\$")}}} */ - def quoteReplacement(text: String): String = Matcher quoteReplacement text + def quoteReplacement(text: String): String = Matcher.quoteReplacement(text) }