scala学习:提取器

scala学习:提取器

unapply 与模式匹配

object EMail {
      def apply(user: String, domain: String): String = user + "@" + domain

      def unapply(string: String): Option[(String, String)] = {
        val strings: Array[String] = string.split("@")
        if (strings.length == 2) Some(strings(0), strings(1)) else None
      }
    }

    def una(x: String): Unit = x match {
      case EMail(user, domain) => println(s"user: $user, domain: $domain")
      case _ => println("is not a email")
    }

    una("ljk@qq.com")
    una("taobao.com")

正则表达式

test("regex test "){

    val decimal = """(-)?(\d+)(\.\d*)?""".r// 可选-,加上一个数字或者多个数字,加上可选的 可能小数点和0个或者多个数字
    val decimal(a,b,c) = "-1.23"

    println(s"a: $a, b: $b, c: $c")
  }

你可能感兴趣的