这段代码有什么问题? Scala - 元组作为函数类型

时间:2013-09-03 03:58:41

标签: scala runtime-error

以下代码有什么问题?我正在尝试使用元组(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) ) =     {
                                           ^

3 个答案:

答案 0 :(得分:2)

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

def find_host ( f : (String, Int) ) = f match {
...                                   ^^^^^^^

答案 1 :(得分: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")
  }
}

答案 2 :(得分: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