1
1

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.

なんちゃってOptionモナド

1
Last updated at Posted at 2013-07-06

Scalaで、値を取得するメソッドから、値の有無を含めた結果としてOption型を返すことが出来ます。

例えば、Scalaだとこうなる

Configuration.scala
// Option型(Optionモナド)を返す側
class Configuration {
    def get(key : String) : Option[String] = {
        val value = System.getProperty(key)
        if (value == null) {
            None
        } else {
            Some(value)
        }
    }
}
Main.scala
// 受け取り側
val conf = new Configuration()
conf.get("url") match {
    case None => {
        // 値が無い場合
    }
    case Some(f) => {
        // 値がある場合
        println(f)    // fには、System.getProperty("url")の結果と同じものが入っている
    }
}

構文そのものの説明は割愛。

こんな感じのものをJavaでもやりたい!!
と思って、考えた結果…

Option.java
public interface Option<T> {
    T get();
     boolean just();
}
Some.java
public class Some<T> implements Option<T> {
    private final T value;
    
    public Some(T value) {
        this.value = value;
    }
    public T get() {
        return this.value;
    }

    public boolean just() {
        return true;
    }
}
None.java
public class None<T> implements Option<T> {
    public None() {
        // do nothing
    }
    
    public T get() throws UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

    public boolean just() {
        return false;
    }
}
Configuration.java
// Option型(Optionモナド)を返す側
public class Configuration {
    public Option<String> get(String key) {
        final String value = System.getProperty(key);
        if (value == null) {
            return new None<String>();
        } else {
            return new Some<String>(value);
        }
    }
}
Main.java
final Configuration config = new Configuration();
final Option<String> opt = config.get("url");
if (opt.just()) {
    System.out.println(opt.get());
} else {
    // 値が無い場合の処理
}

と言った具合になる。
悪くないんだけど、Option#just()でいちいち判定を入れてて、
入れ忘れてOption#get()を呼び出すと例外が飛んでくるって時点で、
nullチェックと変わらないといえば変わらない。。。

ぐるぐるしている型…方の、ブログの方がタイプセーフでいい…けど、コード量多いのが難点。
でも、ScalaでもNoneが返ってきてるときにget()とか呼び出したら、例外飛んでくる点では同じだから、
判定なりは要るのかなぁ・・・
問題は、それを上手く隠蔽して構文上、絶対に記述しないとならないようにするか否かか…

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?