Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: "recursive value ... needs type" but I use Java types only

Tags:

scala

object Rec extends App {
  val outStream = new java.io.ByteArrayOutputStream
  {
    val out = new java.io.PrintStream(new java.io.BufferedOutputStream(outStream))
  }
}

This seemingly simple code causes a compile error:

$ scalac rec.scala
rec.scala:2: error: recursive value out needs type
  val outStream = new java.io.ByteArrayOutputStream
                  ^
one error found

But I don't see what is "recursive."

Scala compiler version 2.11.7 -- Copyright 2002-2013, LAMP/EPFL

Background: I was trying to write a unit test on println with T):T" rel="nofollow">Console.withOut

like image 883
nodakai Avatar asked Feb 21 '26 14:02

nodakai


1 Answers

After putting braces where they belong code looks like this:

object Rec extends App {
  val outStream = new java.io.ByteArrayOutputStream {
    val out = new java.io.PrintStream(new java.io.BufferedOutputStream(outStream))
  }
}

and this is how you create object of an anonymous class with a member out that uses the defined object recursively (outStream uses outStream in its definition).

I believe this is what you wanted to do

object Rec extends App {
  val outStream = new java.io.ByteArrayOutputStream
  val out = new java.io.PrintStream(new java.io.BufferedOutputStream(outStream))
}

If you for some reason need to create another scope, you can use locally

What does Predef.locally do, and how is it different from Predef.identity

like image 154
Łukasz Avatar answered Feb 23 '26 02:02

Łukasz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!