1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Scalaのメソッド1(instanceof、キャスト)

Last updated at Posted at 2016-10-30

scala始めました。instancof系をまとめました。

isInstanceOfメソッド

Javaでいうinstanceof。指定した型が同じであればtrue。それ以外はfalse。

isInstanceOfSample.scala
object isInstanceOfSample {
  def main(args:Array[String]){
    val one : Int = 1
    
    println("Java: one instanceof Int")
    println(one.isInstanceOf[Int])
    println("")
    println("Java: one instanceof Byte")
    println(one.isInstanceOf[Byte])
  }
}

実行結果は

Java: one instanceof Int
true

Java: one instanceof Byte
false

oneはInt型なので、Byte型で比較するともちろんfalseが出る。

asInstanceOfメソッド

Javaでのキャストを意味する。

asInstanceOfSample.scala
object asInstanceOfSample {
  def main(args:Array[String]){
    val one : Int = 789
    
    println("Java: (Byte)one")
    println(one.asInstanceOf[Byte])
  }
}

実行結果

Java: (Byte)one
21

ついでにキャストがうまくいかないと(例えばoneをStringにキャストしてみる)、

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
	at test.asInstanceOfSample$.main(asInstanceOfTest.scala:6)
	at test.asInstanceOfSample.main(asInstanceOfTest.scala)

ClassCastExceptionを投げてくる。

まとめ

Javaだとinstanceofと書いたり括弧でくくったりして気軽にキャストできたが、scalaだとJavaより長くなっている。その理由が、このメソッドを使わず、match式を使ってくれということらしい(^^ゞ

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?