簡體   English   中英

這段代碼有什么問題? Scala-元組作為函數類型

[英]What's wrong with this piece of code? Scala - tuple as function type

以下代碼有什么問題? 我正在嘗試使用元組(字符串, find_host )作為函數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) ) =     {
                                           ^

要進行模式匹配(此處為case語句),您需要告訴編譯器要匹配的內容:

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

此代碼不會編譯失敗。 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")
  }
}

這是另一種解決方案:

注意:這里您不需要告訴編譯器要匹配什么。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM