Skip to content

Instantly share code, notes, and snippets.

@quiye
Last active March 22, 2018 14:56
Show Gist options
  • Save quiye/1b472eebe78262444168f9fbdefa46e8 to your computer and use it in GitHub Desktop.
Save quiye/1b472eebe78262444168f9fbdefa46e8 to your computer and use it in GitHub Desktop.
scala練習

キャストは慎重に

scala> val a: Any = List(1,2,3)
a: Any = List(1, 2, 3)

scala> val d=a.asInstanceOf[List[Long]]
d: List[Long] = List(1, 2, 3)

scala> val e=a.asInstanceOf[List[Int]].map(_.toLong)
e: List[Long] = List(1, 2, 3)

scala> d(0)
java.lang.ClassCastException: java.base/java.lang.Integer cannot be cast to java.base/java.lang.Long
  at scala.runtime.BoxesRunTime.unboxToLong(BoxesRunTime.java:105)
  ... 28 elided

scala> e(0)
res31: Long = 1

キャストが優先される?

scala> val a = List("hello", "tacos").asInstanceOf[List[Int]]
a: List[Int] = List(hello, tacos)

List[Any]でもキャストが優先される?

scala> List(999, "tacos").asInstanceOf[List[Int]]
res40: List[Int] = List(999, tacos)

要素にLongが1つでもあると、List[Long]になるみたい

scala> List(999L, 333).asInstanceOf[List[Long]](1)
res50: Long = 333

scala> List(999, 333L).asInstanceOf[List[Long]](1)
res51: Long = 333

scala> List(999, 333).asInstanceOf[List[Long]](1)
java.lang.ClassCastException: java.base/java.lang.Integer cannot be cast to java.base/java.lang.Long
  at scala.runtime.BoxesRunTime.unboxToLong(BoxesRunTime.java:105)
  ... 28 elided

数値が同じでも型が違う

scala> 9 == 9L
res75: Boolean = true

scala> List(9) == List(9L)
res76: Boolean = true

scala> 9.isInstanceOf[Int] == 9L.isInstanceOf[Int]
res77: Boolean = false

scala> List(9).isInstanceOf[List[Int]] == List(9L).isInstanceOf[List[Int]]
<console>:12: warning: fruitless type test: a value of type List[Long] cannot also be a List[Int] (the underlying of List[Int]) (but still might match its erasure)
       List(9).isInstanceOf[List[Int]] == List(9L).isInstanceOf[List[Int]]
                                                               ^
res79: Boolean = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment