2016-06-21 28 views
0

我目前正在尝试学习如何使用Scala,但我遇到了一些语法问题。使用+运算符时类型不匹配

当我在斯卡拉提示符下键入:

import scala.collection.immutable._ 
var q = Queue[Int](1) 
println((q+1).toString) 

我收到以下错误:

<console>:12: error: type mismatch; 
found : Int(1) 
required: String 
       println((q+1).toString) 

我只是想使用重载+运算符定义如下队列:

def +[B >: A](elem : B) : Queue[B] Creates a new queue with element added at the end of the old queue. Parameters elem - the element to insert

但似乎scala做了字符串连接。所以,你能帮我理解如何将一个元素添加到队列中(不使用完美的入队队列;我想使用+运算符)?也许,你能否给我一些关于这种行为的解释,对初学者来说似乎有点奇怪?

谢谢

+1

你从哪里得到这个定义?这与目前的文档不一致 –

+2

该方法来自某个旧版本的Scala。它在2.9中被删除。使用更新的文档。 – Kolmar

+0

非常感谢。 Google将http://www.scala-lang.org/api/2.5.0/scala/collection/immutable/Queue.html作为“scala队列不可变”的第二个结果。我没那么小心,我没有注意到它是2.5版本。我高估了谷歌搜索引擎的力量:) –

回答

5

您使用了错误的操作符(见docs):

scala> var q = Queue[Int](1) 
q: scala.collection.immutable.Queue[Int] = Queue(1) 

scala> q :+ 2 
res1: scala.collection.immutable.Queue[Int] = Queue(1, 2) 

scala> 0 +: q 
res2: scala.collection.immutable.Queue[Int] = Queue(0, 1) 

由于+操作员给出的类型,Scala的默认字符串连接,让您的类型没有别的意思不匹配错误。