{"id":901,"date":"2015-08-07T09:01:00","date_gmt":"2015-08-07T08:01:00","guid":{"rendered":"http:\/\/benjiweber.co.uk\/blog\/?p=901"},"modified":"2015-08-10T06:06:41","modified_gmt":"2015-08-10T05:06:41","slug":"anonymous-types-in-java","status":"publish","type":"post","link":"https:\/\/benjiweber.co.uk\/blog\/2015\/08\/07\/anonymous-types-in-java\/","title":{"rendered":"Anonymous Types in Java"},"content":{"rendered":"<p class=\"lead\">Java allows casting to an intersection of types, e.g. (Number &#038; Comparable)5. When combined with default methods on interfaces, it provides a way to combine behaviour from multiple types into a single type, without a named class or interface to combine them.<\/p>\n<p>Let&#8217;s say we have two interfaces that provide behaviour for Quack and Waddle.<\/p>\n<pre lang=\"java\">\r\ninterface Quacks {\r\n    default void quack() {\r\n        System.out.println(\"Quack\");\r\n    }\r\n}\r\ninterface Waddles {\r\n    default void waddle() {\r\n        System.out.println(\"Waddle\");\r\n    }\r\n}\r\n<\/pre>\n<p>If we wanted something that did both we&#8217;d normally declare a Duck type that combines them, something like <\/p>\n<pre lang=\"java\">\r\ninterface Duck extends Quacks, Waddles {}\r\n<\/pre>\n<p>However, casting to an intersection of types we can do something like <\/p>\n<pre lang=\"java\">\r\nwith((Anon & Quacks & Waddles)i->i, ducklike -> {\r\n    ducklike.quack();\r\n    ducklike.waddle();\r\n});\r\n<\/pre>\n<p>What&#8217;s going on here? Anon is a functional interface compatible with the identity lambda, so we can safely cast the identity lambda i->i to Anon.<\/p>\n<pre lang=\"java\">\r\ninterface Anon {\r\n    Object f(Object o);\r\n}\r\n<\/pre>\n<p>Since Quacks and Waddles are both interfaces with no abstract methods, we can also cast to those and there&#8217;s still only a single abstract method, which is compatible with our lambda expression. So the cast to (Anon &#038; Quacks &#038; Waddles) creates an anonymous type that can both quack() and waddle().<\/p>\n<p>The with() method is just a helper that also accepts a consumer of our anonymous type and makes it possible to use it.<\/p>\n<pre lang=\"java\">\r\nstatic <T extends Anon> void with(T t, Consumer<T> consumer) {\r\n    consumer.accept(t);\r\n}\r\n<\/pre>\n<p>This also works when calling a method that accepts an intersection type. We might have a method that accepts anything that quacks and waddles.<\/p>\n<pre lang=\"java\">\r\npublic static <Ducklike extends Quacks &#038; Waddles> void doDucklikeThings(Ducklike ducklike) {\r\n    ducklike.quack();\r\n    ducklike.waddle();\r\n}\r\n<\/pre>\n<p>We can now invoke the above method with an intersection cast<\/p>\n<pre lang=\"java\">\r\ndoDucklikeThings((Anon & Quacks & Waddles)i->i);\r\n<\/pre>\n<h2>Source code<\/h2>\n<p>You can find <a href=\"https:\/\/github.com\/benjiman\/java-anonymous-types\/\">complete examples on github<\/a><\/p>\n<h2>Enhancing existing objects<\/h2>\n<p>Some have asked whether one can use this to add functionality to existing objects. This trick only works with lambdas, but we can make use of a delegating lambda, for common types like List that we might want to enhance.<\/p>\n<p>Let&#8217;s say we are fed up of having to call list.stream().map(f).collect(toList()) and wish List had a map() method on it directly.<\/p>\n<p>We could do the following<\/p>\n<pre lang=\"java\">\r\nList<String> stringList = asList(\"alpha\",\"bravo\");\r\nwith((ForwardingList<String> & Mappable<String>)() -> stringList, list -> {\r\n    List<String> strings = list.map(String::toUpperCase);\r\n    strings.forEach(System.out::println);\r\n});\r\n<\/pre>\n<p>Where Mappable<String> declares our new method<\/p>\n<pre lang=\"java\">\r\ninterface Mappable<T> extends DelegatesTo<List<T>> {\r\n    default <R> List<R> map(Function<T,R> mapper) {\r\n        return delegate().stream().map(mapper).collect(Collectors.toList());\r\n    }\r\n}\r\n<\/pre>\n<p>And DelegatesTo<T> is a common ancestor with our ForwardingList <\/p>\n<pre lang=\"java\">\r\ninterface DelegatesTo<T> {\r\n    T delegate();\r\n}\r\ninterface ForwardingList<T> extends DelegatesTo<List<T>>, List<T> {\r\n    default int size() {\r\n        return delegate().size();\r\n    }\r\n    \/\/... and so on\r\n}\r\n<\/pre>\n<p><a href=\"https:\/\/github.com\/benjiman\/java-anonymous-types\/blob\/master\/src\/main\/java\/com\/benjiweber\/anonymous\/EnhancingListExample.java\">Here&#8217;s a full example<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Java allows casting to an intersection of types, e.g. (Number &#038; Comparable)5. When combined with default methods on interfaces, it provides a way to combine behaviour from multiple types into a single type, without a named class or interface to combine them. Let&#8217;s say we have two interfaces that provide behaviour for Quack and Waddle&#8230;.  <a href=\"https:\/\/benjiweber.co.uk\/blog\/2015\/08\/07\/anonymous-types-in-java\/\" class=\"more-link\" title=\"Read Anonymous Types in Java\">Read more &raquo;<\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[8],"tags":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v14.9 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/benjiweber.co.uk\/blog\/2015\/08\/07\/anonymous-types-in-java\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Anonymous Types in Java - Benji&#039;s Blog\" \/>\n<meta property=\"og:description\" content=\"Java allows casting to an intersection of types, e.g. (Number &#038; Comparable)5. When combined with default methods on interfaces, it provides a way to combine behaviour from multiple types into a single type, without a named class or interface to combine them. Let&#8217;s say we have two interfaces that provide behaviour for Quack and Waddle.... Read more &raquo;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/benjiweber.co.uk\/blog\/2015\/08\/07\/anonymous-types-in-java\/\" \/>\n<meta property=\"og:site_name\" content=\"Benji&#039;s Blog\" \/>\n<meta property=\"article:published_time\" content=\"2015-08-07T08:01:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2015-08-10T05:06:41+00:00\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebSite\",\"@id\":\"https:\/\/benjiweber.co.uk\/blog\/#website\",\"url\":\"https:\/\/benjiweber.co.uk\/blog\/\",\"name\":\"Benji&#039;s Blog\",\"description\":\"\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":\"https:\/\/benjiweber.co.uk\/blog\/?s={search_term_string}\",\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/benjiweber.co.uk\/blog\/2015\/08\/07\/anonymous-types-in-java\/#webpage\",\"url\":\"https:\/\/benjiweber.co.uk\/blog\/2015\/08\/07\/anonymous-types-in-java\/\",\"name\":\"Anonymous Types in Java - Benji&#039;s Blog\",\"isPartOf\":{\"@id\":\"https:\/\/benjiweber.co.uk\/blog\/#website\"},\"datePublished\":\"2015-08-07T08:01:00+00:00\",\"dateModified\":\"2015-08-10T05:06:41+00:00\",\"author\":{\"@id\":\"https:\/\/benjiweber.co.uk\/blog\/#\/schema\/person\/45ecb36b51f4ce99e6929d2d31ca5c09\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/benjiweber.co.uk\/blog\/2015\/08\/07\/anonymous-types-in-java\/\"]}]},{\"@type\":\"Person\",\"@id\":\"https:\/\/benjiweber.co.uk\/blog\/#\/schema\/person\/45ecb36b51f4ce99e6929d2d31ca5c09\",\"name\":\"benji\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/benjiweber.co.uk\/blog\/#personlogo\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/05fb47b31a0b329e1b790074a9b624ef?s=96&d=mm&r=g\",\"caption\":\"benji\"}}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","amp_enabled":true,"_links":{"self":[{"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/posts\/901"}],"collection":[{"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/comments?post=901"}],"version-history":[{"count":7,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/posts\/901\/revisions"}],"predecessor-version":[{"id":908,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/posts\/901\/revisions\/908"}],"wp:attachment":[{"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/media?parent=901"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/categories?post=901"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/tags?post=901"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}