{"id":689,"date":"2015-01-14T22:11:05","date_gmt":"2015-01-14T21:11:05","guid":{"rendered":"http:\/\/benjiweber.co.uk\/blog\/?p=689"},"modified":"2015-01-14T22:15:32","modified_gmt":"2015-01-14T21:15:32","slug":"implicit-conversions-with-identity-functions","status":"publish","type":"post","link":"https:\/\/benjiweber.co.uk\/blog\/2015\/01\/14\/implicit-conversions-with-identity-functions\/","title":{"rendered":"Implicit Conversions with Identity Functions"},"content":{"rendered":"<p class=\"lead\">What use is a method that just returns its input? Surprisingly useful. A surprising use is as a way to convert between types.<\/p>\n<p>There&#8217;s a well known trick that&#8217;s often used to work around Java&#8217;s terrible array literals that you may have come across. If you have a method that takes an array as an argument<\/p>\n<pre lang=\"java\">\r\npublic static void foo(String[] anArray) { }\r\n<\/pre>\n<p>Invoking foo requires the ugly<\/p>\n<pre lang=\"java\">\r\nfoo(new String[]{\"hello\", \"world\"});\r\n<\/pre>\n<p>For some reason Java requires the redundant &#8220;new String[]&#8221; here, even though it can be trivially inferred. Fortunately we can work around this with the following method which at first glance might seem pointless.<\/p>\n<pre lang=\"java\">\r\npublic static <T> T[] array(T... input) {\r\n    return input;\r\n}\r\n<\/pre>\n<p>It just returns the input. However it is accepting an array of Type T in the form of a varargs, and returning that array. It becomes useful due as now Java will infer the types and create the array cleanly. We can now call foo like so.<\/p>\n<pre lang=\"java\">\r\nfoo(array(\"hello\", \"world\"));\r\n<\/pre>\n<p>That is a neat trick, but it really becomes useful in Java 8 thanks to structural typing of lambdas\/method references and implicit conversions between types. Here&#8217;s another example of a method that&#8217;s far more useful than it appears at first glance. It just accepts a function and returns the same function.<\/p>\n<pre lang=\"java\">\r\npublic static <T,R> Function<T,R> f(Function<T,R> f) {\r\n    return f;\r\n}\r\n<\/pre>\n<p>The reason it&#8217;s useful is we can pass it any structurally equivalent method reference and have it converted to a java.util.function.Function, which provides us some useful utility methods for function composition. <\/p>\n<p>Here&#8217;s an example. Let&#8217;s say we have a list of Libraries (Collection of Collection of Books)<\/p>\n<pre lang=\"java\">\r\ninterface Library {\r\n    List<Book> books();\r\n    static Library library(Book... books) {\r\n        return () -> asList(books);\r\n    }\r\n}\r\n\r\ninterface Book {\r\n    String name();\r\n    static Book book(String name) { return () -> name; }\r\n}\r\n\r\nList<Library> libraries = asList(\r\n    library(book(\"The Hobbit\"), book(\"LoTR\")),\r\n    library(book(\"Build Quality In\"), book(\"Lean Enterprise\"))\r\n);\r\n<\/pre>\n<p>We can now print out the book titles thusly<\/p>\n<pre lang=\"java\">\r\nlibraries.stream()\r\n    .flatMap(library -> library.books().stream()) \/\/ Stream of libraries to stream of books.\r\n    .map(Book::name) \/\/ Stream of names\r\n    .forEach(System.out::println);  \r\n<\/pre>\n<p>But that flatMap call is upsetting, everything else is using a method reference, not a lambda expression. I&#8217;d really like to write the following, but it won&#8217;t compile because flatMap requires a function that returns a Stream, rather than a function that returns a List.<\/p>\n<pre lang=\"java\">\r\nlibraries.stream()\r\n    .flatMap(Library::books) \/\/ Compile Error, wrong return type.\r\n    .map(Book::name) \r\n    .forEach(System.out::println);  \r\n<\/pre>\n<p>Here&#8217;s where our method that returns its input comes in again. This compiles fine.<\/p>\n<pre lang=\"java\">\r\nlibraries.stream()\r\n    .flatMap(f(Library::books).andThen(Collection::stream)) \r\n    .map(Book::name) \r\n    .forEach(System.out::println);  \r\n    \r\npublic static <T,R> Function<T,R> f(Function<T,R> f) {\r\n    return f;\r\n}\r\n<\/pre>\n<p>This works because Library::books is equivalent to a Function&lt;Library, List&lt;Book&gt;&gt;, so passing it to the f() method implicitly converts it to that type. java.util.function.Function provides an andThen method which returns a new function which composes the two functions. <\/p>\n<p>Now in this trivial example it&#8217;s actually longer to write this than the equivalent lambda, but it can be useful when combining more complex examples.<\/p>\n<p>We can do the same thing with other functional interfaces. For example to allow Predicate composition or negation.<\/p>\n<p>Here we have a handy isChild() method implemented for us on Person, but we really want the inverse &#8211; isAdult() check to pass to the serveAlcohol method. This sort of thing comes up all the time.<\/p>\n<pre lang=\"java\">\r\ninterface Person {\r\n    boolean isChild();\r\n    static Person child() { return () -> true; }\r\n    static Person adult() { return () -> false; }\r\n}\r\n\r\npublic static void serveAlcohol(Person person, Predicate<Person> isAdult) {\r\n    if (isAdult.test(person)) System.out.println(\"Serving alcohol\");\r\n}\r\n<\/pre>\n<p>If we want to reuse Person::isChild we can do the same trick. The p() method converts the method reference to a Predicate for us, and we can then easily negate it.<\/p>\n<pre lang=\"java\">\r\nserveAlcohol(adult(), p(Person::isChild).negate());\r\n\r\npublic static <T> Predicate<T> p(Predicate<T> p) {\r\n    return p;\r\n}\r\n<\/pre>\n<p>Have you got any other good examples?<\/p>\n","protected":false},"excerpt":{"rendered":"<p>What use is a method that just returns its input? Surprisingly useful. A surprising use is as a way to convert between types. There&#8217;s a well known trick that&#8217;s often used to work around Java&#8217;s terrible array literals that you may have come across. If you have a method that takes an array as an&#8230;  <a href=\"https:\/\/benjiweber.co.uk\/blog\/2015\/01\/14\/implicit-conversions-with-identity-functions\/\" class=\"more-link\" title=\"Read Implicit Conversions with Identity Functions\">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":{"footnotes":""},"categories":[8],"tags":[],"class_list":["post-689","post","type-post","status-publish","format-standard","hentry","category-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Implicit Conversions with Identity Functions - Benji&#039;s Blog<\/title>\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\/01\/14\/implicit-conversions-with-identity-functions\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Implicit Conversions with Identity Functions - Benji&#039;s Blog\" \/>\n<meta property=\"og:description\" content=\"What use is a method that just returns its input? Surprisingly useful. A surprising use is as a way to convert between types. There&#8217;s a well known trick that&#8217;s often used to work around Java&#8217;s terrible array literals that you may have come across. If you have a method that takes an array as an... Read more &raquo;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/benjiweber.co.uk\/blog\/2015\/01\/14\/implicit-conversions-with-identity-functions\/\" \/>\n<meta property=\"og:site_name\" content=\"Benji&#039;s Blog\" \/>\n<meta property=\"article:published_time\" content=\"2015-01-14T21:11:05+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2015-01-14T21:15:32+00:00\" \/>\n<meta name=\"author\" content=\"benji\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"benji\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/2015\\\/01\\\/14\\\/implicit-conversions-with-identity-functions\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/2015\\\/01\\\/14\\\/implicit-conversions-with-identity-functions\\\/\"},\"author\":{\"name\":\"benji\",\"@id\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/#\\\/schema\\\/person\\\/45ecb36b51f4ce99e6929d2d31ca5c09\"},\"headline\":\"Implicit Conversions with Identity Functions\",\"datePublished\":\"2015-01-14T21:11:05+00:00\",\"dateModified\":\"2015-01-14T21:15:32+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/2015\\\/01\\\/14\\\/implicit-conversions-with-identity-functions\\\/\"},\"wordCount\":494,\"commentCount\":2,\"articleSection\":[\"Java\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/2015\\\/01\\\/14\\\/implicit-conversions-with-identity-functions\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/2015\\\/01\\\/14\\\/implicit-conversions-with-identity-functions\\\/\",\"url\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/2015\\\/01\\\/14\\\/implicit-conversions-with-identity-functions\\\/\",\"name\":\"Implicit Conversions with Identity Functions - Benji&#039;s Blog\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/#website\"},\"datePublished\":\"2015-01-14T21:11:05+00:00\",\"dateModified\":\"2015-01-14T21:15:32+00:00\",\"author\":{\"@id\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/#\\\/schema\\\/person\\\/45ecb36b51f4ce99e6929d2d31ca5c09\"},\"breadcrumb\":{\"@id\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/2015\\\/01\\\/14\\\/implicit-conversions-with-identity-functions\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/2015\\\/01\\\/14\\\/implicit-conversions-with-identity-functions\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/2015\\\/01\\\/14\\\/implicit-conversions-with-identity-functions\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Implicit Conversions with Identity Functions\"}]},{\"@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\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/#\\\/schema\\\/person\\\/45ecb36b51f4ce99e6929d2d31ca5c09\",\"name\":\"benji\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/417ada828fa4be09324820d24c0d93c3bfcbae183629e09117c9f4c4ab7ed43a?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/417ada828fa4be09324820d24c0d93c3bfcbae183629e09117c9f4c4ab7ed43a?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/417ada828fa4be09324820d24c0d93c3bfcbae183629e09117c9f4c4ab7ed43a?s=96&d=mm&r=g\",\"caption\":\"benji\"},\"sameAs\":[\"http:\\\/\\\/benjiweber.co.uk\"],\"url\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/author\\\/benji\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Implicit Conversions with Identity Functions - Benji&#039;s Blog","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/benjiweber.co.uk\/blog\/2015\/01\/14\/implicit-conversions-with-identity-functions\/","og_locale":"en_US","og_type":"article","og_title":"Implicit Conversions with Identity Functions - Benji&#039;s Blog","og_description":"What use is a method that just returns its input? Surprisingly useful. A surprising use is as a way to convert between types. There&#8217;s a well known trick that&#8217;s often used to work around Java&#8217;s terrible array literals that you may have come across. If you have a method that takes an array as an... Read more &raquo;","og_url":"https:\/\/benjiweber.co.uk\/blog\/2015\/01\/14\/implicit-conversions-with-identity-functions\/","og_site_name":"Benji&#039;s Blog","article_published_time":"2015-01-14T21:11:05+00:00","article_modified_time":"2015-01-14T21:15:32+00:00","author":"benji","twitter_card":"summary_large_image","twitter_misc":{"Written by":"benji","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/benjiweber.co.uk\/blog\/2015\/01\/14\/implicit-conversions-with-identity-functions\/#article","isPartOf":{"@id":"https:\/\/benjiweber.co.uk\/blog\/2015\/01\/14\/implicit-conversions-with-identity-functions\/"},"author":{"name":"benji","@id":"https:\/\/benjiweber.co.uk\/blog\/#\/schema\/person\/45ecb36b51f4ce99e6929d2d31ca5c09"},"headline":"Implicit Conversions with Identity Functions","datePublished":"2015-01-14T21:11:05+00:00","dateModified":"2015-01-14T21:15:32+00:00","mainEntityOfPage":{"@id":"https:\/\/benjiweber.co.uk\/blog\/2015\/01\/14\/implicit-conversions-with-identity-functions\/"},"wordCount":494,"commentCount":2,"articleSection":["Java"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/benjiweber.co.uk\/blog\/2015\/01\/14\/implicit-conversions-with-identity-functions\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/benjiweber.co.uk\/blog\/2015\/01\/14\/implicit-conversions-with-identity-functions\/","url":"https:\/\/benjiweber.co.uk\/blog\/2015\/01\/14\/implicit-conversions-with-identity-functions\/","name":"Implicit Conversions with Identity Functions - Benji&#039;s Blog","isPartOf":{"@id":"https:\/\/benjiweber.co.uk\/blog\/#website"},"datePublished":"2015-01-14T21:11:05+00:00","dateModified":"2015-01-14T21:15:32+00:00","author":{"@id":"https:\/\/benjiweber.co.uk\/blog\/#\/schema\/person\/45ecb36b51f4ce99e6929d2d31ca5c09"},"breadcrumb":{"@id":"https:\/\/benjiweber.co.uk\/blog\/2015\/01\/14\/implicit-conversions-with-identity-functions\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/benjiweber.co.uk\/blog\/2015\/01\/14\/implicit-conversions-with-identity-functions\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/benjiweber.co.uk\/blog\/2015\/01\/14\/implicit-conversions-with-identity-functions\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/benjiweber.co.uk\/blog\/"},{"@type":"ListItem","position":2,"name":"Implicit Conversions with Identity Functions"}]},{"@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":{"@type":"EntryPoint","urlTemplate":"https:\/\/benjiweber.co.uk\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/benjiweber.co.uk\/blog\/#\/schema\/person\/45ecb36b51f4ce99e6929d2d31ca5c09","name":"benji","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/417ada828fa4be09324820d24c0d93c3bfcbae183629e09117c9f4c4ab7ed43a?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/417ada828fa4be09324820d24c0d93c3bfcbae183629e09117c9f4c4ab7ed43a?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/417ada828fa4be09324820d24c0d93c3bfcbae183629e09117c9f4c4ab7ed43a?s=96&d=mm&r=g","caption":"benji"},"sameAs":["http:\/\/benjiweber.co.uk"],"url":"https:\/\/benjiweber.co.uk\/blog\/author\/benji\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/posts\/689","targetHints":{"allow":["GET"]}}],"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=689"}],"version-history":[{"count":11,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/posts\/689\/revisions"}],"predecessor-version":[{"id":700,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/posts\/689\/revisions\/700"}],"wp:attachment":[{"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/media?parent=689"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/categories?post=689"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/tags?post=689"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}