3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

java.net.URLのgetメソッドの戻り値をオプション型にするScala用ラッパー

Posted at

java.net.URLのgetメソッドで取得できるURLの部分でお気づきのとおり、getメソッドの中には存在しない場合の戻り値がnullだったり-1だったりするものがある。Scalaで使うなら「存在しない場合」はNoneで受け取りたい。そこで、java.net.URL用のラッパーを作った。

implicit class ScalaURL(url: java.net.URL) {
  def query: Option[String] = url.getQuery match {
    case null      => None
    case q: String => Some(q)
  }

  def path: Option[String] = url.getPath match {
    case ""        => None
    case p: String => Some(p)
  }

  def userInfo: Option[String] = url.getUserInfo match {
    case null      => None
    case u: String => Some(u)
  }

  def authority: String = url.getAuthority

  def port: Option[Int] = url.getPort match {
    case -1     => None
    case p: Int => Some(p)
  }

  def defaultPort: Option[Int] = url.getDefaultPort match {
    case -1     => None
    case p: Int => Some(p)
  }

  def protocol: String = url.getProtocol

  def host: String = url.getHost

  def file: Option[String] = url.getFile match {
    case ""        => None
    case f: String => Some(f)
  }

  def ref: Option[String] = url.getRef match {
    case null      => None
    case r: String => Some(r)
  }
}
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?