首页 > 解决方案 > Getting strange behaviour converting a Seq to a String in my message handler

问题描述

I am doing some logging in the receive for a particular message I receive and am getting some bizarre behaviour. My code goes something like this:

case class Message(id: Int, items: Seq[Item])

def receive = {
  case Message(id, items) =>
    log.debug(s"Message received[$id]: $items");
}

Occasionally I get the following exception in the line where I log:

scala java.lang.UnsupportedOperationException: tail of empty stream

Unfortunately I didn't manage to save the full stack trace and it is not something that happens regularly. But I can say it originates in immutable.Stream.toString which comes from the call to convert items to a string

This despite the fact there are items in my Seq and I never intended for it to be a stream. The items originate in a Map and I create my message by doing something like the following:

val map: Map[Int, Item]
...
es.publish(Message(id, map.values.toSeq))

Why is the string conversion for the logging treating it like a stream? And is there an issue with sending streams in akka messages?

标签: scalaakka

解决方案


Map.values返回 anIterabletoSeqfrom TraversableOncetoStream当您调用toSeq.

这是 Seq 抽象或 Stream 抽象的问题。但是你想看看它。List 和 Stream 都实现了 Seq,但对某些操作有不同的行为。想象一下有一个无限的 Stream 并且你在它上面调用 .tail 。它永远不会回来。

我倾向于不再使用 Seq,而是到处使用 List。在我想要流行为的地方明确地流。


推荐阅读