From the course: Pattern Matching for Switch in Java 21
Unlock this course with a free trial
Join today to access over 25,500 courses taught by industry experts.
Motivation: Pattern matching for instanceof - Java Tutorial
From the course: Pattern Matching for Switch in Java 21
Motivation: Pattern matching for instanceof
- [Instructor] You saw how the traditional instance of operator works. In the traditional instance of operator, it only takes in a type like string, for example. Pattern matching was introduced to be used with the instance of operator where it is extended to take a type pattern instead of just a type. What's a type pattern? Consider this. If obj instance of string is on the right hand side, it's a type pattern. Here the pattern is a test or predicate plus a target and a pattern variable. By the way, a predicate is a bullion valued function with one argument. For example, here, the instance of operator testing if the obj argument is a string is a predicate. Target is the argument of the predicate. For example, obj here. Pattern variable source data about the target only if the predicate returns true. For example, the pattern variable is s here, so the type pattern is String s here. Here is how it works. The instance of operator matches the target object to the type pattern in this…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.