Skip to content

Instantly share code, notes, and snippets.

@ababup1192
Last active January 8, 2017 10:09
Show Gist options
  • Save ababup1192/9cce8a1a70d8d53e00126f133b30b7f6 to your computer and use it in GitHub Desktop.
Save ababup1192/9cce8a1a70d8d53e00126f133b30b7f6 to your computer and use it in GitHub Desktop.
object Main extends App {
def myif(p: => Boolean)(thenS: => Any)(elseS: => Any): Any = {
var res: Any = null
val result = p && { res = thenS; true} || { res = elseS; false}
res
}
def myelse(elseS: => Any): Any = {
elseS
}
println(myif(1 != 1){
"aaaaa"
}( myelse {
"bbbbb"
}))
}
@gakuzzzz
Copy link

gakuzzzz commented Jan 8, 2017

else つけてもつけなくてもOKだしAnyにならない版です

scala> :paste
// Entering paste mode (ctrl-D to finish)

object MyIfElse {

  sealed trait IfResult[+A] {
    def `else`[B >: A](exp: => B): B = this match {
      case Then(result) => result
      case Else         => exp
    }
  }
  private case class Then[+A](result: A) extends IfResult[A]
  private case object Else extends IfResult[Nothing]

  def `if`[A](p: Boolean)(exp: => A): IfResult[A] = p match {
    case true => Then(exp)
    case _    => Else
  }

}

// Exiting paste mode, now interpreting.

defined module MyIfElse

scala> import MyIfElse._
import MyIfElse._

scala> val a = `if` (10 > 11) { println("then"); "AAA" } `else` { println("else"); "BBB" }
else
a: String = BBB

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment