Scala:“递归值......需要类型"但我只使用 Java 类型 [英] Scala: "recursive value ... needs type" but I use Java types only

查看:44
本文介绍了Scala:“递归值......需要类型"但我只使用 Java 类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 编译器版本 2.11.7 -- 版权所有 2002-2013,LAMP/EPFL

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

背景:我尝试使用 Console.withOut

Background: I was trying to write a unit test on println with Console.withOut

推荐答案

将大括号放在它们所属的位置后,代码如下所示:

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))
  }
}

这就是你如何创建一个匿名类的对象,它的成员 out 递归地使用定义的对象(outStream 使用 outStream in它的定义).

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).

我相信这就是你想做的

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

什么是 Predef.locally 做,和 Predef.identity 有什么区别

这篇关于Scala:“递归值......需要类型"但我只使用 Java 类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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