What Is Java Interface Equivalent in Ruby

What is java interface equivalent in Ruby?

Ruby has Interfaces just like any other language.

Note that you have to be careful not to conflate the concept of the Interface, which is an abstract specification of the responsibilities, guarantees and protocols of a unit with the concept of the interface which is a keyword in the Java, C# and VB.NET programming languages. In Ruby, we use the former all the time, but the latter simply doesn't exist.

It is very important to distinguish the two. What's important is the Interface, not the interface. The interface tells you pretty much nothing useful. Nothing demonstrates this better than the marker interfaces in Java, which are interfaces that have no members at all: just take a look at java.io.Serializable and java.lang.Cloneable; those two interfaces mean very different things, yet they have the exact same signature.

So, if two interfaces that mean different things, have the same signature, what exactly is the interface even guaranteeing you?

Another good example:

package java.util;

interface List<E> implements Collection<E>, Iterable<E> {
void add(int index, E element)
throws UnsupportedOperationException, ClassCastException,
NullPointerException, IllegalArgumentException,
IndexOutOfBoundsException;
}

What is the Interface of java.util.List<E>.add?

  • that the length of the collection does not decrease
  • that all the items that were in the collection before are still there
  • that element is in the collection

And which of those actually shows up in the interface? None! There is nothing in the interface that says that the Add method must even add at all, it might just as well remove an element from the collection.

This is a perfectly valid implementation of that interface:

class MyCollection<E> implements java.util.List<E> {
void add(int index, E element)
throws UnsupportedOperationException, ClassCastException,
NullPointerException, IllegalArgumentException,
IndexOutOfBoundsException {
remove(element);
}
}

Another example: where in java.util.Set<E> does it actually say that it is, you know, a set? Nowhere! Or more precisely, in the documentation. In English.

In pretty much all cases of interfaces, both from Java and .NET, all the relevant information is actually in the docs, not in the types. So, if the types don't tell you anything interesting anyway, why keep them at all? Why not stick just to documentation? And that's exactly what Ruby does.

Note that there are other languages in which the Interface can actually be described in a meaningful way. However, those languages typically don't call the construct which describes the Interface "interface", they call it type. In a dependently-typed programming language, you can, for example, express the properties that a sort function returns a collection of the same length as the original, that every element which is in the original is also in the sorted collection and that no bigger element appears before a smaller element.

So, in short: Ruby does not have an equivalent to a Java interface. It does, however, have an equivalent to a Java Interface, and it's exactly the same as in Java: documentation.

Also, just like in Java, Acceptance Tests can be used to specify Interfaces as well.

In particular, in Ruby, the Interface of an object is determined by what it can do, not what class is is, or what module it mixes in. Any object that has a << method can be appended to. This is very useful in unit tests, where you can simply pass in an Array or a String instead of a more complicated Logger, even though Array and Logger do not share an explicit interface apart from the fact that they both have a method called <<.

Another example is StringIO, which implements the same Interface as IO and thus a large portion of the Interface of File, but without sharing any common ancestor besides Object.

Is a Ruby module equivalent to a Java Interface?

I think I'd equate a module to something more akin to an extension method in C#. You're adding functionality to an existing class that is actually defined elsewhere. There isn't an exact analog in either C# or Java, but I definitely wouldn't think of it as an interface because the implementation is derived as well as the interface.

In Ruby, what is the equivalent to an interface in C#?

There are no interfaces in ruby since ruby is a dynamically typed language. Interfaces are basically used to make different classes interchangeable without breaking type safety. Your code can work with every Console as long it behaves like a console which in C# means implements IConsole. "duck typing" is a keyword you can use to catch up with the dynamic languages way of dealing with this kind of problem.

Further you can and should write unit tests to verify the behavior of your code. Every object has a respond_to? method you can use in your assert.

how do you create an interface in ruby?

There is no real concept of an interface in Ruby. Instead, people tend to just write general methods that don't care about the type of the objects they are operating on, and just use some specific set of methods that the object will need to implement.

For example:

def add(a,b)
a+b
end

The add method doesn't care if its arguments are integers, strings, or arrays. They just have to be some object that implements the + operator.

def calltwice(obj)
obj.call
obj.call
end

The calltwice method doesn't care if obj is a lambda, proc, or some custom class. It just cares that the object has a call method.

You can informally define an interface in the comments by telling the users of your code what methods will be called an how they should behave.

Is there a way to enforce the implementation of interface methods in Ruby?

Ruby doesn't have any interface similar to Java. With duck-typing, it's up to each class to decide if it answers a method call or not.

If you want to show that a method should be implemented in a subclass, you could raise an exception in the parent method :

class User
def authenticated?(*p)
raise NotImplementedError, "IMPLEMENT ME IN #{self.class}##{__method__}"
end
end

class InternalUser < User
end

InternalUser.new.authenticated?('user', 'user@test.com')
#interface.rb:3:in `authenticated?': IMPLEMENT ME IN InternalUser#authenticated? (NotImplementedError)

What's the equivalent of ruby blocks in java

How to do this in Java?

There is no equivalent to Ruby blocks in Java. Ruby blocks are syntactically lightweight, semantically lightweight, and they are not objects. They are mostly syntactic constructions with some lightweight semantics behind. In this, they are more like an enhanced for loop in Java.

The closest equivalent you have in Java, would be a functional interface combined with a lambda expression. Something like this, using one of the pre-defined functional interfaces from the java.util.function package, namely the interface java.util.function.Consumer<T>:

void myf(int i, java.util.function.Consumer<Integer> proc) {
System.out.println("start");
proc.accept(i);
System.out.println("end");
}

You use it like this:

myf(3, i -> System.out.println(i * 10));
myf(4, i -> System.out.println(i - 10));
// start
// 30
// end
// start
// -6
// end

However, this is not equivalent to Ruby's blocks. This is equivalent to Ruby's Procs and lambda literals, in other words, it is more equivalent to this:

def myf(i, proc)
puts "start"
proc.(i)
puts "end"
end

myf(3, -> i { puts i * 10 })
myf(4, -> i { puts i - 10 })

# start
# 30
# end
# start
# -6
# end

Note that myf in your example does not use the result of the block, so modeling it with java.util.function.Function<T, R> would be incorrect. Consumer<T> is the correct interface to use for a "function" (more a procedure, really) that "consumes" its argument but doesn't return anything, whereas Function<T, R> is the correct interface to use for a function that takes one argument and returns a result.

Create a variable of interface type in jRuby

Firstly, MyInterface intrf = ConcreteClass.new is not valid Ruby. MyInterface is a constant (such as a constant reference to a class, although it could be a reference to any other type), not a type specifier for a reference - Ruby and hence JRuby is dynamically typed.

Secondly, I assume you want to write a JRuby class ConcreteClass which implements the Java interface MyInterface, which – for example here – I'm saying is in the the Java package 'com.example'.

require 'java'
java_import 'com.example.MyInterface'

class ConcreteClass
# Including a Java interface is the JRuby equivalent of Java's 'implements'
include MyInterface

# You now need to define methods which are equivalent to all of
# the methods that the interface demands.

# For example, let's say your interface defines a method
#
# void someMethod(String someValue)
#
# You could implements this and map it to the interface method as
# follows. Think of this as like an annotation on the Ruby method
# that tells the JRuby run-time which Java method it should be
# associated with.
java_signature 'void someMethod(java.lang.String)'
def some_method(some_value)
# Do something with some_value
end

# Implement the other interface methods...
end

# You can now instantiate an object which implements the Java interface
my_interface = ConcreteClass.new

See the JRuby wiki for more details, in particular the page JRuby Reference.

What does a Java static method look like in Ruby?

Anders' answer is correct, however for utility methods like mean you don't need to use a class, you can put the method in a module:

module MyUtils
def self.mean(values)
# implementation goes here
end
end

The method would be called in the same way:

avg = MyUtils.mean([1,2,3,4,5])

Equivalent of Ruby #map or #collect in Java?

There's the map method on streams which takes a method argument.

collection.stream()
.map(obj -> obj.someMethod())
.collect(Collectors.toList()));

map returns another stream so in order to retrieve the list you have call the collect method.

Too much to explain in a post, but you can visit this link which helped me out a lot:

http://winterbe.com/posts/2014/03/16/java-8-tutorial/



Related Topics



Leave a reply



Submit