![]() ![]() It’s demonstrated in Chapter 15 like this: Val arrayOfObject = objects.asInstanceOf] It can be used in more complicated code, such as when you need to interact with Java and send it an array of Object instances: The asInstanceOf method isn’t limited to only these situations. Val microphone = cm.lookup("microphone").asInstanceOf Val cm = new ConfigurationManager("config.xml") In a manner similar to Spring, this requires reading an XML configuration file, then casting instances to the specific types you want: With this library, many properties are defined in an XML file, and then you create recognizer and microphone objects dynamically. The example shown in the Solution comes from code I wrote to work with an open source Java speech recognition library named Sphinx-4. Val emailAccount = yaml.load(text).asInstanceOf Val yaml = new Yaml(new Constructor(classOf)) It’s used when reading a YAML configuration file: Val cat = ctx.getBean("cat").asInstanceOf Val dog = ctx.getBean("dog").asInstanceOf instantiate our dog and cat objects from the application context Val ctx = new ClassPathXmlApplicationContext("applicationContext.xml") open/read the application context file This approach is needed when using the Spring Framework and instantiating beans from an application context file: In dynamic programming, it’s often necessary to cast from one type to another. The asInstanceOf method is defined in the Scala Any class and is therefore available on all objects. Recognizer recognizer = (Recognizer)cm.lookup("recognizer") This Scala code is equivalent to the following Java code: Val recognizer = cm.lookup("recognizer").asInstanceOf In the following example, the object returned by the lookup method is cast to an instance of a class named Recognizer: ![]() Use Scala’s asInstanceOf method to cast an instance to the desired type. You need to cast an instance of a Scala class from one type to another, such as when creating objects dynamically. This is Recipe 6.1, “How to cast an object from one type to another (object casting).” Problem This is an excerpt from the 1st Edition of the Scala Cookbook (partially modified for the internet). show more info on classes/objects in repl. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |