簡體   English   中英

執行模式匹配時,Scala類型不匹配

[英]Scala type mismatch while doing pattern matching

我正在嘗試進行符合預期的模式匹配,但是IntelliJ IDE顯示以下突出顯示錯誤

 Expected: PartialFunction[Regex, NotInferedB], actual: Nothing => Boolean. Cannot resolve method x.unapply Cannot resolve symbol x 

碼:

 scala>  val keys = Map(
         |          "XYZ" -> List("(?i)(.*SANDWICH.*)",
         |            "(?i)(.*BURGER.*)").map(x => x.r)
         |        )

    keys: scala.collection.immutable.Map[String,List[scala.util.matching.Regex]] = Map(XYZ -> List((?i)(.*SANDWICH.*), (?i)(.*BURGER.*)))

    scala> val desc = "I DON't LIKE SANDWICH "
    desc: String = "I DON't LIKE SANDWICH "

    scala> if (keys("XYZ").collect{x => desc match{ case x(key) => true}}.contains(true)) println("yes") else println("no")
    yes

錯誤顯示在收集部分中。 任何人都可以指導我,因為可能是導致IntelliJ中突出顯示錯誤的問題是什么

獲得PartialFunction[Regex, NotInferedB], actual: Nothing => Boolean編譯時間,因為您提供的是lambda函數,而collect函數采用PartialFunction。

我不知道您希望通過這段代碼實現什么,但是下面的代碼可以解決您的問題。

if (keys("XYZ").collect { case x => true }.contains(true)) println("yes") else println("no")
  • 這是寫您最后一個表達式的正確方法:

if (keys("XYZ").collect{case x: Regex => desc match{ case x(_) => true} }.contains(true)) println("yes") else println("no")

  • 但是有一種更好的編寫方式:

    if(keys("XYZ").exists { x => x.findFirstMatchIn(desc) match { case Some(_) => true case None => false } }) println("yes") else println("no")

嘗試這個:

if (keys("XYZ").exists(_.findFirstIn(desc).isDefined)) println("yes") else println("no")

暫無
暫無

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

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