Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
777 views
in Technique[技术] by (71.8m points)

scala - Type mismatch (String) using case class and actor

Some format issue when I'm trying to quote the code, so here is the picture :(

image description here

import akka.actor.{Actor, ActorSystem, Props}

case class Number(n: Int)
case class String(s: String)

class DoublingActor extends Actor {
  def receive: Receive = {
    case Number(n) => println(s"Result of doubling $n: ${n*2}")
    case String(s) => println(s"Result of doubling $s: ${s}${s}")
  }
}

object Double extends App {
  val system = ActorSystem("DoublerSystme")
  val doubler = system.actorOf(Props[DoublingActor], "doubler")

  doubler ! Number(5)
  doubler ! String("test")
}

The thing is, the actor works fine with number, but how can I add the matching function that returns the string twice?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should avoid naming your case class as String, especially in your case, with String parameter type:

case class String(s: String)

It would confuse the compiler to expect a parameter type different from the actual String type you want. Your app will work if you explicitly specify java.lang.String as the parameter type:

case class String(s: java.lang.String)

In any case, I would not recommend naming a case class as String.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...