• [^] # Re: Très bon

    Posté par (site web personnel) . En réponse au journal Java 7 est dispo !. Évalué à 1.

    Pour le fun, si on voulait faire la même chose en Scala :

    scala> implicit def pouet[A](a:A) = new { def !![B<:AnyRef](f:A=>B):B = if (a != null) f(a) else null.asInstanceOf[B] }
    pouet: [A](a: A)java.lang.Object{def !![B <: AnyRef](f: (A) => B): B}
    scala> "lapin" !! (_.toUpperCase) !! (_ drop 2)
    res21: String = PIN
    scala> "lapin" !! (_.toUpperCase) !! (_ drop 2) !! (s => if (s.contains("grut")) "youpy" else null) !! (_.reverse)
    res22: String = null
    scala> "lapin" !! (_.toUpperCase) !! (_ drop 2) !! (s => if (s.contains("IN")) "youpy" else null) !! (_.reverse)
    res23: String = ypuoy
    
    ..
    ..
    ..
    

    Mais en général on n'utilise pas "null" en Scala, on utilise le type Option :

    scala> Some("lapin") map (_.toUpperCase) map (_ drop 2) flatMap (s => if (s.contains("IN")) Some("youpy") else None) map (_.reverse)
    res24: Option[String] = Some(ypuoy)
    scala> Some("lapin") map (_.toUpperCase) map (_ drop 2) flatMap (s => if (s.contains("grut")) Some("youpy") else None) map (_.reverse)
    res25: Option[String] = None