Module: JrubyScala::CoreExt::OperatorTranslations

Included in:
Java::JavaLang::Object
Defined in:
lib/jruby_scala/core_ext/operator_translations.rb

Overview

Provides translations between the standard set of Ruby operators and their Scala counterparts allowing the natural use of Ruby operators on Scala objects.

Currently, translates the ruby-style array/hash access operator #[] and handles Proc methods on objects that extend scala.FunctionN. Other operators may be added as necessary.

Examples:

Ruby-style hash access

h = scala.collection.immutable.HashMap.new
h = h.update(0, 4)
puts h[0]   --> 4

Constant Summary collapse

OPERATORS =

A mapping of ruby operators to their respective method invocations in Scala

{
"=" => "$eq",
">" => "$greater",
"<" => "$less",
"+" => "$plus",
"-" => "$minus",
"*" => "$times",
"/" => "div",
"!" => "$bang",
"@" => "$at",
"#" => "$hash",
"%" => "$percent",
"^" => "$up",
"&" => "$amp",
"~" => "$tilde",
"?" => "$qmark",
"|" => "$bar",
"\\" => "$bslash"}

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



38
39
40
41
# File 'lib/jruby_scala/core_ext/operator_translations.rb', line 38

def self.included(base)
  alias_method :method_missing_without_scala_operator_translations, :method_missing
  alias_method :method_missing, :method_missing_with_scala_operator_translations
end

Instance Method Details

#method_missing_with_scala_operator_translations(sym, *args) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/jruby_scala/core_ext/operator_translations.rb', line 43

def method_missing_with_scala_operator_translations(sym, *args)
  if sym == :[] or (sym == :call and type_of_scala_function?(self))
    apply(*args)
  elsif sym == :arity and (ar = type_of_scala_function?(self))
    ar
  elsif sym == :binding and type_of_scala_function?(self)
    binding
  elsif sym == :to_proc and type_of_scala_function?(self)
    self
  else
    str = sym.to_s
    str = $&[1] + '_=' if str =~ /^(.*[^\]=])=$/
    OPERATORS.each {|from, to| str.gsub!(from, to)}
  
    if respond_to?(str)
      send(str.to_sym, *args)
    else
      method_missing_without_scala_operator_translations(sym, *args)
    end
  end
end