Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to hide Scala Class from Import

Tags:

scala

Wrote this code

scala> import scala.collection.immutable.{Stream => _}
scala> Stream(1, 2, 3)
res0: scala.collection.immutable.Stream[Int] = Stream(1, ?)

But shouldn't the second line fail? because I hid the Stream class from import in line 1? why is it still visible?

I also tried

scala> import scala.collection.immutable.{Stream => DoNotUse}
import scala.collection.immutable.{Stream=>DoNotUse}

scala> Stream(1, 2, 3)
res1: scala.collection.immutable.Stream[Int] = Stream(1, ?)

Again, this is still visible.

like image 460
Knows Not Much Avatar asked Nov 06 '22 22:11

Knows Not Much


1 Answers

Here's an example with the new -Yimports in 2.13.

$ cat S.scala

package mystream

class Stream[A]

object MyPredef {
  type Stream[A] = mystream.Stream[A]
}

Imports later in the list shadow earlier ones:

$ scala -Yimports:java.lang,scala,scala.Predef,mystream.MyPredef
Welcome to Scala 2.13.0 (OpenJDK 64-Bit Server VM 11.0.1)

scala> new Stream[Int]
res0: mystream.Stream[Int] = mystream.Stream@65fe2691

It's not as convenient as the hypothetical syntax

-Yimports:java.lang._,scala.{Stream=>_, _},scala.Predef._

which would support your use case more directly.

Alternatively, it's usual to put aliases in an enclosing package object:

package object mystuff {
  type Stream[A] = mystream.Stream[A]
}

and

scala> :pa
// Entering paste mode (ctrl-D to finish)

package mystuff {
  class C { def f = new Stream[Int] }
}

// Exiting paste mode, now interpreting.


scala> new mystuff.C().f
res1: mystream.Stream[Int] = mystream.Stream@715fa8c5

but the alias is scoped to those subpackages and not any compilation unit.

like image 172
som-snytt Avatar answered Nov 14 '22 23:11

som-snytt