Exploring the world of functional programming in Java can be a rewarding experience, especially

I am seeking a method to define generic computation on a data set and have the compiler alert me if there are any errors.

Having experience with TypeScript, I have seen that you can achieve something like this:

/**
 * Type inferred as:
 * Array<{
 *   a: number;
 *   b: string;
 *   c: { d: number; e: string };
 * }>
 */
const data = [
  { a: 1, b: "b", c: { d: 4, e: "e" } },
  { a: 2, b: "b", c: { d: 4, e: "e" } },
  { a: 3, b: "b", c: { d: 4, e: "e" } },
];

const result = data
  // change the type of c to string
  .map(o => ({...o, c: JSON.stringify(o.c)}))
  // adding a new field
  .map(o => ({...o, d: "new"}))
;
/** 
 * `result` type is automatically inferred as:
 * Array<{
 *     d: string;
 *     c: string;
 *     a: number;
 *     b: string;
 * }>
 */

After applying these transformations, the type of result will be accurately inferred along with each type within map.

The advantage here is that the compiler aids in identifying potential bugs.

Is it possible to achieve similar functionality in Java?

My attempt involved using a generic Map object with a spanning generic type across various lower-level types resembling a JS dictionary. Yet, the compiler lacks understanding that key X is actually of type Y, rendering it ineffective in bug detection.

It seems that replicating the same level of static analysis in Java as we have in TypeScript is not feasible. The Java compiler does not excel at updating unnamed types along the way and capturing such bugs.

Answer №1

In contrast to Java, TypeScript (as well as JavaScript) is fundamentally different in its approach.

Within the realm of TypeScript/JavaScript, Objects play a central role, whereas in the domain of Java, the focus is on Classes.

In Java, creating an object instantly isn't feasible (unlike in TypeScript/JavaScript).

In Java, one must first define a class or even a specialized version known as a record. Although there are workarounds such as using anonymous inner classes or obtaining instances of specific subtypes, these methods have limitations when it comes to defining new Generic parameters on-the-fly while creating an object.

To cater to custom generic types, you can utilize either a class or leverage features like the Java 16 record which ensures immutability.

Creating a Generic Class

A generic class mirroring the structure of an enclosing object { a; b; c; } could look like this:

public class MyType<A, B, C> {
    private A a;
    private B b;
    private C c;
    
    // constructor, getters, etc.
}

Generating a Generic Record

The internal object with the pattern { d; e; } can be represented through a record (Note: canonical constructors and utility methods are automatically generated by the compiler for records):

public record Pair<L, R>(L left, R right) {}

Note: Libraries like Vavr and Apache Commons provide types such as Triple and Pair, although not within JDK. The standard JDK's Map.Entry may serve as a partial replacement, but semantic distinctions would still persist between domain type and map entry.

Type Inference

Type inference principles exist in Java under concepts like Target type and poly expressions. Propagation of type information within code involves context-specific situations such as assignment, invocation, or casting contexts.

A demonstration of type inference includes examples with Java 10's Local variable type inference via var and Java 7's diamond <> operator (assuming constructors for both no-args and all-args are declared):

MyType<Integer, String, Pair<Integer, String>> myType = new MyType<>();
        
var myType2 = new MyType<>(1, "b", new Pair<>(4, "e")); 
// Using <> implies - infer the type of generic parameters

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on setting an attribute value with JavaScriptExecutor in Selenium WebDriver

I am attempting to set an attribute value for all instances of the same type of <img> tag on My website, for example: <img src="images/temp/advertisement.png"> and I want to set style="display: none" so that I can hide them. I have tried the ...

How can we use the Selenium JavascriptExecutor in Java to return an Object from JavaScript?

I've encountered an issue while running a JavaScript file using Java with Selenium in my application. When I execute the JavaScript file with JavascriptExecutor after logging in, I'm only getting a null return instead of a valid one. Below is a ...

Output a message to the Java console once my Selenium-created Javascript callback is triggered

My journey with Javascript has led me to mastering callback functions and grasping the concept of 'functional programming'. However, as a newcomer to the language, I struggle to test my syntax within my IntelliJ IDE. Specifically, I am working on ...

The module located at "c:/Users//Desktop/iooioi/src/main/webapp/node_modules/rxjs/Rx" does not have a default export available

I am currently delving into the realm of RxJs. Even after installing rxjs in package.json, why am I still encountering an error that says [ts] Module '"c:/Users//Desktop/iooioi/src/main/webapp/node_modules/rxjs/Rx"' has no default export ...

Is it possible for Angular2 to map a lone JSON object?

Dealing with a JSON response that is a single object, rather than an array, can be tricky. Recently in my project, I encountered a situation where I needed to map and use such a response from an API to fill out a template. It seemed like a simple task at f ...

Is there a way to change a .pptx document into a base64 string?

Currently, I am working on a project that involves creating an addin for Office. The challenge I am facing is opening other pptx files from within the addin. After some research, I discovered that I need to use base64 for the PowerPoint.createPresentation( ...

Ensuring type signatures are maintained when wrapping Vue computed properties and methods within the Vue.extend constructor

Currently, I am trying to encapsulate all of my defined methods and computed properties within a function that tracks their execution time. I aim to keep the IntelliSense predictions intact, which are based on the type signature of Vue.extend({... Howeve ...

The Material UI button shifts to a different row

I need help adjusting the spacing between text and a button on my webpage. Currently, they are too close to each other with no space in between. How can I add some space without causing the button to move to the next line? const useStyles = makeStyles((the ...

What is the best method to display a tooltip for a disabled radio button within a set of radio buttons?

Is there a way to disable a specific radio button based on a condition and display a tooltip only for that disabled button? https://i.stack.imgur.com/niZK1.png import {Tooltip} from '@mui/material'; <Tooltip titl ...

Initiate the process of displaying data on a datetime chart using Highcharts

I am currently developing a yearly chart, but I've encountered a small issue. The chart begins in January, however there is no data available until May. The client specifically wants the chart to only display when there is data available, and unfortu ...

Is it necessary to include async/await in a method if there is already an await keyword where it is invoked?

Here are the two methods I have written in Typescript: async getCertURL(pol: string): Promise<string> { return await Api.getData(this.apiUrl + pol + this.certEndpoint, {timeout: 60000}).then( (response) => { return response.data.certUR ...

Transforming JSON data into a visually appealing pie chart using highcharts

I'm having trouble loading my JSON string output into a highcharts pie chart category. The chart is not displaying properly. Here is the JSON string I am working with: var json = {"{\"name\":\"BillToMobile\"}":{"y":2.35},"{\ ...

Preventing data binding for a specific variable in Angular 2: Tips and tricks

How can I prevent data binding for a specific variable? Here's my current approach: // In my case, data is mostly an object. // I would prefer a global solution function(data) { d = data; // This variable changes based on user input oldD = da ...

Modifying iframe src using click event from a separate component in Angular 10

I am looking to dynamically update the src attribute of an iframe when the menu bar is clicked. The menu bar resides in a separate component and includes a dropdown menu for changing languages. Depending on which language is selected, I want to update the ...

In Angular components, data cannot be updated without refreshing the page when using setInterval()

Here's the Angular component I'm working with: export class UserListComponent implements OnInit, OnDestroy { private _subscriptions: Subscription; private _users: User[] = []; private _clickableUser: boolean = true; constructor( priv ...

Utilizing properties from the same object based on certain conditions

Here's a perplexing query that's been on my mind lately. I have this object with all the styles I need to apply to an element in my React app. const LinkStyle = { textDecoration : 'none', color : 'rgba(58, 62, 65, 1)', ...

typescript defining callback parameter type based on callback arguments

function funcOneCustom<T extends boolean = false>(isTrue: T) { type RETURN = T extends true ? string : number; return (isTrue ? "Nice" : 20) as RETURN; } function funcCbCustom<T>(cb: (isTrue: boolean) => T) { const getFirst = () => ...

Hover shows no response

I'm having trouble with my hover effect. I want an element to only be visible when hovered over, but it's not working as expected. I've considered replacing the i tag with an a, and have also tried using both display: none and display: bloc ...

Ways to pass data to a different module component by utilizing BehaviourSubject

In multiple projects, I have used a particular approach to pass data from one component to another. However, in my current project, I am facing an issue with passing data from a parent component (in AppModule) to a sidebar component (in CoreModule) upon dr ...

Unsuccessful Invocation of Servlet by Ajax Function

I have a situation where I am trying to trigger an Ajax javascript function from my jsp file, with the intention of loading a servlet for further processing. The issue I am facing is that even though I am able to pass values from the jsp to the ajax functi ...