Scala #009: asInstanceOf
|中級篇|
Java.use(better, src=Scala) # ソースコードの歩き方《中級篇》
ソースコードの歩き方《Scala2.8.0》
《著》小粒ちゃん@湘南組、小粒ちゃん@博多組《監修》小泉ひよ子とタマゴ倶楽部
第1版♪2010/07/14
|関連記事|
Scala #009: asInstanceOf
》作業中です《
■ リスト項目を選択する
49: val cb = source --- ComboBoxDemo.scala:50: error: value selection is not a member of scala.swing.Component val petName = cb.selection.item.mkString ^ one error foundsource は、scala.swing.Component のインスタンスと見なされ、メンバー selection を持たないので、エラーになります。そこで、
46: object Command extends Publisher { 47: reactions += { 48: case SelectionChanged(source) => 49: val cb = source.asInstanceOf[ComboBox[String]] 50: val petName = cb.selection.item.mkString 51: updateLabel(petName) 52: } 53: }
asInstanceOf を利用して、scala.swing.Component を scala.swing.ComboBox のインスタンスと見なすことで、この問題を回避します。
■ scala.collection.mutable.ArrayBuffer
54 object Map extends ImmutableMapFactory[Map] {
55
56 /** $mapCanBuildFromInfo */
57 implicit def canBuildFrom[A, B]: CanBuildFrom[Coll, (A, B), Map[A, B]] = new MapCanBuildFrom[A, B]
58
59 def empty[A, B]: Map[A, B] = EmptyMap.asInstanceOf[Map[A, B]]
■ scala.swing.ComboBox
161 class ComboBox[A](items: Seq[A]) extends Component with Publisher { 162 override lazy val peer: JComboBox = new JComboBox(ComboBox.newConstantModel(items)) with SuperMixin 163 164 object selection extends Publisher { 165 def index: Int = peer.getSelectedIndex 166 def index_=(n: Int) { peer.setSelectedIndex(n) } 167 def item: A = peer.getSelectedItem.asInstanceOf[A] 168 def item_=(a: A) { peer.setSelectedItem(a) }
選択された項目 item は、asInstanceOf によって、型 A のインスタンスと見なされます。
■ scala.Enumeration
196 private def nameOf(i: Int): String = synchronized { 197 def isValDef(m: java.lang.reflect.Method) = 198 getClass.getDeclaredFields.exists(fd => fd.getName == m.getName && 199 fd.getType == m.getReturnType) 200 nmap.get(i) match { 201 case Some(name) => name 202 case None => 203 val methods = getClass.getMethods 204 for (m <- methods 205 if (classOf[Value].isAssignableFrom(m.getReturnType) && 206 !java.lang.reflect.Modifier.isFinal(m.getModifiers) && 207 m.getParameterTypes.isEmpty && 208 isValDef(m))) { 209 val name = m.getName 210 // invoke method to obtain actual `Value` instance 211 val value = m.invoke(this) 212 // invoke `id` method 213 val idMeth = classOf[Val].getMethod("id") 214 val id: Int = idMeth.invoke(value).asInstanceOf[java.lang.Integer].intValue() 215 nmap += (id -> name) 216 } 217 nmap(i) 218 } 219 }
》作業中です《