Skip to content

Instantly share code, notes, and snippets.

@hyunjun
Last active November 19, 2020 05:32
Show Gist options
  • Save hyunjun/9041c3294b6d4a8417a3a4451f1f1539 to your computer and use it in GitHub Desktop.
Save hyunjun/9041c3294b6d4a8417a3a4451f1f1539 to your computer and use it in GitHub Desktop.
Scala test
❯ scala
Welcome to Scala 2.12.8 (OpenJDK 64-Bit Server VM, Java 1.8.0_192).
Type in expressions for evaluation. Or try :help.

scala> import scala.util.Try
import scala.util.Try

scala> def div(s1: Option[String], s2: Option[String]): Option[Int] = {
     |   for {
     |     a <- Try(s1.map(_.toInt)).toOption
     |     b <- Try(s2.map(_.toInt)).toOption
     |     l <- a
     |     r <- b if r != 0
     |     res = l / r
     |   } yield res
     | }
div: (s1: Option[String], s2: Option[String])Option[Int]

scala> div(Some("1"), Some("2"))
res1: Option[Int] = Some(0)

scala> div(Some("1"), Some("0"))
res2: Option[Int] = None

scala> div(Some("1"), Some("0.1"))
res3: Option[Int] = None

scala> div(Some("1"), Some("100"))
res4: Option[Int] = Some(0)

scala> div(Some("1000"), Some("100"))
res5: Option[Int] = Some(10)
  • https://twitter.com/not_xuwei_k/status/1328535431642804226/photo/1

  • test

    ❯ cat A.scala B.scala
    class A {
      val b = 10L
    }
    class B {
      def b = 10L
    }
    
    ❯ javap -c A
    Compiled from "A.scala"
    public class A {
      public long b();
        Code:
           0: aload_0
           1: getfield      #13                 // Field b:J
           4: lreturn
    
      public A();
        Code:
           0: aload_0
           1: invokespecial #19                 // Method java/lang/Object."<init>":()V
           4: aload_0
           5: ldc2_w        #20                 // long 10l
           8: putfield      #13                 // Field b:J
          11: return
    }
    
    ❯ javap -c B
    Compiled from "B.scala"
    public class B {
      public long b();
        Code:
           0: ldc2_w        #11                 // long 10l
           3: lreturn
    
      public B();
        Code:
           0: aload_0
           1: invokespecial #18                 // Method java/lang/Object."<init>":()V
           4: return
    }
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment