zoukankan      html  css  js  c++  java
  • Option

    package option
    
    sealed trait Option[+A] {
    
      def map[B](f: A => B): Option[B] = this match {
        case None    => None
        case Some(a) => Some(f(a))
      }
    
      def flatMap[B](f: A => Option[B]): Option[B] = this match {
        case None    => None
        case Some(a) => f(a)
      }
    
      def getOrElse[B >: A](default: => B): B = this match {
        case None    => default
        case Some(a) => a
      }
    
      def orElse[B >: A](ob: => Option[B]): Option[B] = this match {
        case None => ob
        case _    => this
      }
    
      def filter(f: A => Boolean): Option[A] = this match {
        case Some(a) if (f(a)) => this
        case _                 => None
      }
    }
    
    case class Some[+A](get: A) extends Option[A]
    
    case object None extends Option[Nothing]
    
    object Run {
    
      def main(args: Array[String]): Unit = {
        val some = Some(1.01000)
        val none = None: Option[Double]
    
        println(some.map(_ + 1))
        println(none.map(_ + 1))
    
        println(some.flatMap(x => Some(x + 1)))
        println(none.flatMap(x => Some(x + 1)))
    
        println(some.getOrElse("3.14"))
        println(none.getOrElse("3.14"))
    
        println(some.orElse(Some(1.414)))
        println(none.orElse(Some(1.414)))
    
        println(some.filter(x => x == 1.01))
        println(none.filter(x => x == 1.01))
    
      }
    
    }
    Some(2.01)
    None
    Some(2.01)
    None
    1.01
    3.14
    Some(1.01)
    Some(1.414)
    Some(1.01)
    None
  • 相关阅读:
    Jquery Ajax 调用 WebService
    Dapper.NET
    HTML5 canvas标签
    SQL内外左右交叉连接
    水晶报表纵向重复
    AngularJS 菜鸟
    什么是MVC框架?
    伪类和伪元素的区别
    常用的本地存储-----cookie篇
    JavaScript中基本数据类型和引用数据类型的区别
  • 原文地址:https://www.cnblogs.com/JonkeyGuan/p/5426404.html
Copyright © 2011-2022 走看看