0

以下代码有什么问题?我正在尝试使用元组 (String, Int) 作为函数的输入类型find_host。编译器没有给我任何错误,但是当我运行程序时,我得到了一个。我在这里想念什么?

  def find_host ( f : (String, Int) ) =     {
    case ("localhost", 80 ) => println( "Got localhost")
    case _  => println ("something else")
  }

  val hostport = ("localhost", 80)

  find_host(hostport)

      missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: ?
  def find_host ( f : (String, Int) ) =     {
                                           ^
4

3 回答 3

2

要进行模式匹配(您的 case 语句在这里),您需要告诉编译器要匹配的内容:

def find_host ( f : (String, Int) ) = f match {
...                                   ^^^^^^^
于 2013-09-03T04:03:09.650 回答
1

这是另一个解决方案:

注意:这里你不需要告诉编译器要匹配什么。

scala> def find_host: PartialFunction[(String, Int), Unit] = {
     |   case ("localhost", 80) => print("Got localhost")
     |   case _ => print("Something else")
     | }
find_host: PartialFunction[(String, Int),Unit]

scala> find_host(("localhost", 80))
Got localhost

或者这个:

scala> def find_host: ((String, Int)) => Unit = {
     |   case ("localhost", 80) => print("Got localhost")
     |   case _ => print("Something else")
     | }
find_host: ((String, Int)) => Unit

scala> find_host(("localhost", 80))
Got localhost
于 2013-09-03T04:56:22.517 回答
1

此代码确实无法编译。IntelliJ 的 Scala 支持并不完美;你不能指望它找到所有的编译错误。

如果您在 REPL 中尝试,这就是您得到的结果:

scala>   def find_host ( f : (String, Int) ) =     {
     |     case ("localhost", 80 ) => println( "Got localhost")
     |     case _  => println ("something else")
     |   }
<console>:7: error: missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: ?
         def find_host ( f : (String, Int) ) =     {
                                                   ^

就像 Shadowlands 的回答说的那样,你在f match偏函数之前就失踪了。

而且,由于这个方法返回Unit,所以不要用等号定义它。

def find_host(f: (String, Int)) {
  f match {
    case ("localhost", 80) => println("Got localhost")
    case _  => println("something else")
  }
}
于 2013-09-03T04:35:13.270 回答